Configuring Redis Cache with Spring Boot Application

In this article we will talk about how to configure Redis cache with Spring Boot Application.

Redis can be hosted in a any cloud environment. This post doesnot cover Redis Cache but configuring the Redis Cache . Details about Redis Cache and it’s set up can be found in https://redis.io/

Java Version: 1.8

Spring Boot Version: 1.5.1.RELEASE

  • Add the below jar dependencies in pom.xml file of Spring boot application :

                  org.springframework.data

                  spring-data-redis

                  1.8.0.RELEASE

                  redis.clients

                  jedis

                  2.9.0

  • Create a configuration file and it should extend CachingConfigurerSupport
  • Add the annotation @EnableCaching

@Configuration

@EnableCaching

public class Application extends CachingConfigurerSupport

@Configuration tells the container that Application class has more than one Bean and can be processed to generate bean definations.

@EnableCaching informs container to look for cache manager bean by type.

  • Define Redis connectionfactory with connection details of the Redis cluster.We can set multiple connecting nodes in the list .

     @Bean

public RedisConnectionFactory connectionFactory() {

List nodeList = Arrays.asList(“Redis_domain_url:port”);

         return new JedisConnectionFactory(new RedisClusterConfiguration(nodeList));

}

  • Define the Redis template which serializes and deserializes the objects in Redis.

@Bean

publicRedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf,

StringRedisSerializer stringRedisSerializer) {

RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();

redisTemplate.setConnectionFactory(cf);

redisTemplate.setKeySerializer(stringRedisSerializer);

return redisTemplate;

}

  • Define StringRedisSerializer bean to convert String to bindary and vice versa.

     @Bean

      public StringRedisSerializer stringRedisSerializer() {

               return new StringRedisSerializer();

}

  • Define cache Manager with the redistemplate defined above. We can also set the expiration ttl which will define how long the value will reside in cache .It is in seconds.

      @Bean

public CacheManager cacheManager(RedisTemplate redisTemplate) {

RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);

cacheManager.setDefaultExpiration(3600);

return cacheManager;

}

  • We can set a keyGenerator for generating specific keys in Redis. This will be called as part of cachingConfigurerSupport Below snippet creates key with the  method name as the parameter .

      @Bean

public KeyGenerator keyGenerator() {

return new KeyGenerator() {

@Override

public Object generate(Object o, Method method, Object… objects) {

// This will generate a unique key of the class name, the method

// name,

// and all method parameters appended.

StringBuilder sb = new StringBuilder();

sb.append(“test”);

sb.append(“-“);

sb.append(o.getClass().getSimpleName());

sb.append(“-“);

sb.append(method.getName());

for (Object obj : objects) {

sb.append(obj.toString());

}

LOGGER.debug(“Cache Keys :: ” + sb.toString());

return sb.toString();

}

};

}

  • Add the annotation @Cacheable(value=”cacheNames”) before the method whose return type needs to be cached . Value Attribute is the cache Names in which cache key value pair is stored .

@Cacheable(value=” cacheNames”)

@Override

public List retrieveEmployeeListFromDB(String employeeId) {

… code to retrieve employeeList from DB

}

Digiprove sealCopyright secured by Digiprove © 2019 Geeks 18

Be the first to comment

Leave a Reply

Your email address will not be published.


*