Spring boot uses redis cache

Keywords: Redis Spring Jedis SpringBoot

1. pom import dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

2. redis configuration

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

      StringRedisTemplate template = new StringRedisTemplate(factory);
      template.setValueSerializer(jackson2JsonRedisSerializer);
      template.afterPropertiesSet();
      return template;
    }

    /**
    * Custom CacheManager
    */
    @Bean
     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
@Cacheable("product")
@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
@CachePut(value = "product", key = "#root.targetClass+'-'+#product.id")

//It is applied to the method of removing data, such as deletion method
@CacheEvict 
@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