2

How can I configure Redis caching with Spring Boot. From what I have heard, it's just some changes in the application.properties file, but don't know exactly what.

2 Answers 2

5

To use Redis caching in your Spring boot application all you need to do is set these in your application.properties file

spring.cache.type=redis
spring.redis.host=localhost //add host name here
spring.redis.port=6379

Add this dependency in your 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. That is all is needed to use redis in a Spring boot application. You can use it in any class by autowiring the CacheManager in this case RedisCacheManager.

@Autowired
RedisCacheManager redisCacheManager;
Sign up to request clarification or add additional context in comments.

Comments

1

You can mention all the required properties that is hostname, port etc. in the application.properties file and then read from it.

@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;
}

}

4 Comments

I think, this is not the Spring Boot way. In Spring Boot we don't need to create all these cache manager and stuffs (from what I have read and heard)
I guess this gives you more flexibility in configuration.
that is true, but I need the Spring Boot way
did you find the spring boot way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.