Spring boot 2.0 Redis 集成

使用默认的lettuce 做Redis的链接客户端,value序列化 使用自定义的FastJsonRedisSerializer

加入依赖方面注意加入commons-pool2
lettuce 使用了commons-pool2的连接池

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
     <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
        <version>2.5.0</version>
    </dependency>


public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {

public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

private Class<T> clazz;

public FastJsonRedisSerializer(Class<T> clazz) {
    super();
    this.clazz = clazz;
}

@Override
public byte[] serialize(T t) throws SerializationException {
    if (null == t) {
        return new byte[0];
    }
    return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}

@Override
public T deserialize(byte[] bytes) throws SerializationException {
    if (null == bytes || bytes.length <= 0) {
        return null;
    }
    return JSON.parseObject(bytes, clazz);
}

}

定义CacheConfig
@Bean
public KeyGenerator wiselyKeyGenerator() {
return (target, method, params) -> Joiner.on("").join(target.getClass().getName(), method.getName(), params);

}


@Bean
public RedisTemplate<String, String> redisTemplate(
        RedisConnectionFactory factory) {
    StringRedisTemplate template = new StringRedisTemplate(factory);
    FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);

    template.setValueSerializer(fastJsonRedisSerializer);
    template.setKeySerializer(new StringRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setConnectionFactory(factory);
    template.afterPropertiesSet();

    return template;
}

@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
            .RedisCacheManagerBuilder
            .fromConnectionFactory(redisConnectionFactory);
    return builder.build();
}