[英]How to configure Redis caching in Spring Boot?
How can I configure Redis caching with Spring Boot. 如何使用Spring Boot配置Redis缓存 From what I have heard, it's just some changes in the
application.properties
file, but don't know exactly what. 据我所知,这只是
application.properties
文件中的一些更改,但不知道到底是什么。
To use Redis
caching in your Spring boot application all you need to do is set these in your application.properties
file 要在Spring引导应用程序中使用
Redis
缓存,只需在application.properties
文件中进行设置即可。
spring.cache.type=redis
spring.redis.host=localhost //add host name here
spring.redis.port=6379
Add this dependency in your pom.xml
在您的
pom.xml
添加此依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Additionally, you have to use the @EnableCaching
on your main application class and use the @Cacheable
annotation on the methods to use the Cache. 此外,您必须使用
@EnableCaching
在您的主要应用类别及使用@Cacheable
注释的方法来使用Cache。 That is all is needed to use redis
in a Spring boot application. 这是在Spring Boot应用程序中使用
redis
所需要的。 You can use it in any class by autowiring the CacheManager in this case RedisCacheManager. 您可以在任何类中通过自动装配CacheManager来使用它,在这种情况下为RedisCacheManager。
@Autowired
RedisCacheManager redisCacheManager;
You can mention all the required properties that is hostname, port etc. in the application.properties file and then read from it. 您可以在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;
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.