要在Spring Boot项目中配置Redis作为缓存,你需要遵循以下步骤:
- 添加依赖
在你的pom.xml
文件中添加Spring Boot和Redis的依赖:
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis org.redisson redisson 3.16.1
- 配置Redis连接
在application.properties
或application.yml
文件中配置Redis连接信息:
# application.properties spring.redis.host=localhost spring.redis.port=6379
或者
# application.yml spring: redis: host: localhost port: 6379
- 启用Spring Cache
在你的主类上添加@EnableCaching
注解,以启用缓存功能:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
- 使用Redis作为缓存
在你的服务类中,使用@Cacheable
注解来标记需要缓存的方法。例如:
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class UserService { @Cacheable(value = "https://www.yisu.com/ask/users", key = "#id") public User getUserById(Long id) { // 从数据库或其他数据源获取用户信息 User user = new User(); user.setId(id); user.setName("User " + id); return user; } }
在这个例子中,getUserById
方法的结果将被缓存到名为users
的Redis键中,缓存的键由方法的参数id
生成。
- 配置缓存管理器
如果你需要自定义缓存配置,可以在配置类中创建一个CacheManager
bean。例如:
import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import java.time.Duration; @Configuration @EnableCaching public class CacheConfig { private final RedisConnectionFactory redisConnectionFactory; public CacheConfig(RedisConnectionFactory redisConnectionFactory) { this.redisConnectionFactory = redisConnectionFactory; } @Bean public RedisCacheManager cacheManager() { RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(60)); // 设置缓存有效期为60分钟 return RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(config) .build(); } @Bean public RedisTemplateredisTemplate() { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); return template; } }
这个配置类创建了一个RedisCacheManager
bean,并设置了缓存的默认有效期为60分钟。同时,还创建了一个RedisTemplate
bean,用于操作Redis数据。
现在你已经成功配置了Spring Boot项目以使用Redis作为缓存。你可以根据需要调整缓存配置和使用更多的缓存注解。