Some solutions to using Redis in Spring Boot 2.0

Abstract: Spring Boot has been upgraded from 1.5.x to 2.0. There are some changes. If you don't pay attention, you will jump into the pit. In the Redis module, upgrading from 1.5.x to 2.0, if you do not pay attention to the changes, you will encounter changes in the CacheManager configuration.

Before Spring Boot 1.5.x, there were many tutorials and examples for the configuration of Redis modules, such as Pure Smile's blog and Programmer DD's blog .

Before SpringBoot1.5x, the Redis configuration was as follows:

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... 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 CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        return redisCacheManager;
    }
}

This is the dividing line =============================================

The cache config of Spring Boot 2.0 has changed a lot, and the build mode is generally used.

@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
    RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).build();
    return redisCacheManager;
}

/**
  * @Description: Prevent the problem of garbled serialization in redis storage
  * @return return type
  * @date 2018/4/12 10:54
  */
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
    redisTemplate.setConnectionFactory(redisConnectionFactory);
    redisTemplate.setKeySerializer(new StringRedisSerializer());//key序列化
    redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));  //value序列化
    redisTemplate.afterPropertiesSet();
    return redisTemplate;
}

As for some encapsulation operations of redis, I won't go into details.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325111871&siteId=291194637