微信登录

Redis 集成 - 缓存使用 - 使用 Redis 作为缓存

Java - Web - Spring 《Redis 集成 - 缓存使用 - 使用 Redis 作为缓存》

一、引言

在 Web 应用开发中,缓存是提升系统性能的关键技术之一。Redis 作为一款高性能的内存数据库,以其快速读写、丰富的数据结构和持久化能力,成为了缓存方案的热门选择。在 Spring 框架中集成 Redis 并使用它作为缓存,可以显著减少数据库的访问压力,提高系统的响应速度。本文将详细介绍如何在 Spring 项目中集成 Redis 并使用它作为缓存,同时给出具体的演示代码。

二、环境准备

在开始之前,我们需要确保以下环境已经安装和配置好:

  1. JDK 1.8 或更高版本
  2. Maven 3.x
  3. Redis 服务器

三、Spring 项目中集成 Redis

3.1 创建 Spring Boot 项目

可以使用 Spring Initializr(https://start.spring.io/)来快速创建一个 Spring Boot 项目,添加以下依赖:

  1. <dependencies>
  2. <!-- Spring Boot Web -->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-web</artifactId>
  6. </dependency>
  7. <!-- Spring Boot Data Redis -->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-data-redis</artifactId>
  11. </dependency>
  12. <!-- Spring Cache -->
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-cache</artifactId>
  16. </dependency>
  17. </dependencies>

3.2 配置 Redis 连接信息

application.propertiesapplication.yml 中配置 Redis 连接信息,以下是 application.yml 的示例:

  1. spring:
  2. redis:
  3. host: localhost
  4. port: 6379
  5. password: # 如果有密码则填写

3.3 启用缓存注解

在 Spring Boot 主应用类上添加 @EnableCaching 注解,开启缓存功能:

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.cache.annotation.EnableCaching;
  4. @SpringBootApplication
  5. @EnableCaching
  6. public class RedisCacheApplication {
  7. public static void main(String[] args) {
  8. SpringApplication.run(RedisCacheApplication.class, args);
  9. }
  10. }

四、使用 Redis 作为缓存

4.1 定义缓存服务接口和实现类

创建一个简单的用户服务接口和实现类,用于演示缓存的使用:

  1. // UserService.java
  2. public interface UserService {
  3. String getUserById(String id);
  4. }
  5. // UserServiceImpl.java
  6. import org.springframework.cache.annotation.Cacheable;
  7. import org.springframework.stereotype.Service;
  8. @Service
  9. public class UserServiceImpl implements UserService {
  10. @Cacheable(value = "users", key = "#id")
  11. @Override
  12. public String getUserById(String id) {
  13. // 模拟从数据库中获取用户信息
  14. System.out.println("从数据库中获取用户信息,id: " + id);
  15. return "User: " + id;
  16. }
  17. }

在上述代码中,@Cacheable 注解表示该方法的结果会被缓存。value 属性指定了缓存的名称,key 属性指定了缓存的键,这里使用方法的参数 id 作为键。

4.2 创建控制器

创建一个控制器来调用用户服务:

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.PathVariable;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. public class UserController {
  7. @Autowired
  8. private UserService userService;
  9. @GetMapping("/users/{id}")
  10. public String getUserById(@PathVariable String id) {
  11. return userService.getUserById(id);
  12. }
  13. }

4.3 测试缓存功能

启动 Spring Boot 应用,访问 http://localhost:8080/users/1,第一次访问时,控制台会输出“从数据库中获取用户信息,id: 1”,表示数据是从数据库中获取的。再次访问相同的 URL,控制台不会再输出该信息,说明数据是从缓存中获取的。

五、其他常用缓存注解

除了 @Cacheable 注解,Spring 还提供了其他常用的缓存注解:
| 注解 | 描述 |
| —— | —— |
| @CachePut | 更新缓存中的数据,无论缓存中是否存在该数据,都会执行方法并将结果更新到缓存中。 |
| @CacheEvict | 从缓存中移除数据,可以指定移除单个或多个缓存项。 |
| @Caching | 组合多个缓存注解,可以同时使用多个 @Cacheable@CachePut@CacheEvict 注解。 |

以下是 @CachePut@CacheEvict 的示例代码:

  1. import org.springframework.cache.annotation.CacheEvict;
  2. import org.springframework.cache.annotation.CachePut;
  3. import org.springframework.cache.annotation.Cacheable;
  4. import org.springframework.stereotype.Service;
  5. @Service
  6. public class UserService {
  7. @Cacheable(value = "users", key = "#id")
  8. public String getUserById(String id) {
  9. System.out.println("从数据库中获取用户信息,id: " + id);
  10. return "User: " + id;
  11. }
  12. @CachePut(value = "users", key = "#id")
  13. public String updateUser(String id, String newUser) {
  14. System.out.println("更新用户信息,id: " + id);
  15. return newUser;
  16. }
  17. @CacheEvict(value = "users", key = "#id")
  18. public void deleteUser(String id) {
  19. System.out.println("删除用户信息,id: " + id);
  20. }
  21. }

六、总结

通过本文的介绍,我们学习了如何在 Spring 项目中集成 Redis 并使用它作为缓存。使用 Redis 作为缓存可以有效减少数据库的访问压力,提高系统的性能和响应速度。同时,Spring 提供的缓存注解使得缓存的使用变得非常简单和方便。在实际开发中,可以根据具体的业务需求选择合适的缓存注解来实现缓存功能。

希望本文对你理解和使用 Redis 作为 Spring 项目的缓存有所帮助。

Redis 集成 - 缓存使用 - 使用 Redis 作为缓存