您的位置:宽带测速网 > 网络知识 > SpringBoot中怎么使用Redis做缓存

SpringBoot中怎么使用Redis做缓存

2025-06-21 09:55来源:互联网 [ ]

在SpringBoot中使用Redis做缓存可以通过以下步骤实现:

    添加依赖:首先在pom.xml文件中添加Spring Data Redis的依赖,如下所示:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
    配置Redis连接:在application.properties或application.yml文件中配置Redis连接信息,如下所示:
spring.redis.host=localhostspring.redis.port=6379
    使用Redis缓存:在需要使用缓存的方法上添加@Cacheable注解,示例如下:
@Servicepublic class UserService {@Autowiredprivate UserRepository userRepository;@Cacheable(value = "users", key = "#userId")public User getUserById(Long userId) {return userRepository.findById(userId).orElse(null);}}

在上面的示例中,@Cacheable注解表示该方法会使用名为“users”的缓存,key为userId的缓存键。当方法被调用时,如果缓存中已经存在对应的值,则直接返回缓存中的值,否则执行方法体并将结果存入缓存。

通过以上步骤,就可以在SpringBoot中使用Redis作为缓存了。需要注意的是,需要确保Redis服务器已经启动并且与SpringBoot应用程序正常连接。