一&m; id dot;背景描述
spring 的 @ cache able 已成为我们比较常用的缓存 数据 的方式,但是把非String对象缓存到 redis 后在使用RedisDesktopManager等 软件 查看缓存的数据的时候 展示的是HEX 数据,观察起来比较不方便,所以我们这里自定义了FastJsonRedisSerializer 序列化对象后缓存到redis,可以更 方便的观察缓存数据。
二·引入jar包
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>fastJson</artifactId><version>1.2.17</version></dependency>
三· 代码
1·自定义序列化方式
import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.serializer.SerializerFeature;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.SerializationException;import java.nio.charset.Charset;/**
* 说明:自定义redis序列化方式
*
* @author WangBin
* @version V1.0
* @since 2018.03.22
*/publicclassFastJsonRedisSerializer<T>implementsRedisSerializer<T>{publicstaticfinalCharset DEFAULT_CHARSET =Charset.forName("UTF-8");privateClass<T> clazz;publicFastJsonRedisSerializer(Class<T> clazz){super();this.clazz = clazz;}@Overridepublicbyte[] serialize(T t)throwsSerializationException{if(t ==null){returnnewbyte[0];}return JSON.toJSONString(t,SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);}@Overridepublic T deserialize(byte[] bytes)throwsSerializationException{if(bytes ==null|| bytes.length <=0){returnnull;}String str =newString(bytes, DEFAULT_CHARSET);return JSON.parseObject(str, clazz);}}
2· 配置
import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheConfiguration;import org.springframework.data.redis.serializer.RedisSerializationContext;import java.time.Duration;/**
*
* @author WangBin
* @version V1.0
* @date 2017.12.05
*/@Configuration@EnableCachingpublicclassRedisConfigextendsCachingConfigurerSupport{/**
* 设置 redis 数据默认过期时间
* 设置@cacheable 序列化方式
* @return
*/@BeanpublicRedisCacheConfiguration redisCacheConfiguration(){FastJsonRedisSerializer<Object> fastJsonRedisSerializer =newFastJsonRedisSerializer<>(Object.class);RedisCacheConfiguration configuration =RedisCacheConfiguration.defaultCacheConfig();
configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofDays(30));return configuration;}}