Spring boot uses redis cache

Keywords: Redis Spring Jedis SpringBoot

1. pom import dependency


2. redis configuration

public class RedisConfig extends CachingConfigurerSupport {
    * Custom redis key generation policy
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            for (Object obj : params) {
            return sb.toString();
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
      ObjectMapper om = new ObjectMapper();
      om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      //redis serialization
      Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

      StringRedisTemplate template = new StringRedisTemplate(factory);
      return template;

    * Custom CacheManager
     public CacheManager cacheManager(RedisTemplate redisTemplate) {
         //Global redis cache expiration time
         RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1));  
         RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);

3. Use of notes

@Cacheable(value = {"product","order"}, key = "#root.targetClass+'-'+#id")
@Cacheable(value = "product", key = "#root.targetClass+'-'+#id")
Customizing the cacheManager
@Cacheable(value = "product", key = "#root.targetClass+'-'+#id" cacheManager="cacheManager")

//Apply to methods for writing data, such as adding / modifying methods
@CachePut(value = "product", key = "#root.targetClass+'-'+#product.id")

//It is applied to the method of removing data, such as deletion method
@CacheEvict(value = "product", key = "#root.targetClass+'-'+#id")

Spring Cache provides some SpEL context data for us to use. The following table is directly excerpted from spring official documents:

Be careful:
  when integrating redis with springboot and using @ Cacheable, an error is reported: java.lang.ClassCastException
Solution: it's due to the dependency of hot deployment. Just comment it out.

Posted by savedlema on Tue, 05 Nov 2019 10:44:31 -0800