【发布时间】:2017-12-28 03:43:17
【问题描述】:
如何使用 Spring Boot 配置 Redis 缓存。据我所知,这只是application.properties 文件中的一些更改,但不知道具体是什么。
【问题讨论】:
标签: java spring caching spring-boot redis
如何使用 Spring Boot 配置 Redis 缓存。据我所知,这只是application.properties 文件中的一些更改,但不知道具体是什么。
【问题讨论】:
标签: java spring caching spring-boot redis
要在 Spring Boot 应用程序中使用 Redis 缓存,您只需在 application.properties 文件中设置这些内容
spring.cache.type=redis
spring.redis.host=localhost //add host name here
spring.redis.port=6379
在你的pom.xml中添加这个依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
此外,您必须在主应用程序类上使用@EnableCaching,并在使用缓存的方法上使用@Cacheable 注释。这就是在 Spring 引导应用程序中使用 redis 所需要的一切。在本例中为 RedisCacheManager,您可以通过自动装配 CacheManager 在任何类中使用它。
@Autowired
RedisCacheManager redisCacheManager;
【讨论】:
您可以在 application.properties 文件中提及主机名、端口等所有必需的属性,然后从中读取。
@Configuration
@PropertySource("application.properties")
public class SpringSessionRedisConfiguration {
@Value("${redis.hostname}")
private String redisHostName;
@Value("${redis.port}")
private int redisPort;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(redisHostName);
factory.setPort(redisPort);
factory.setUsePool(true);
return factory;
}
@Bean
RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
@Bean
RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
return redisCacheManager;
}
}
【讨论】: