转自 https://blog.csdn.net/b376924098/article/details/79820642
一·背景描述
spring 的 @cacheable 已成为我们比较常用的缓存数据的方式,但是把非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.38</version> </dependency>
ps:导入fastjson 某些版本运行时会报com.alibaba.fastjson.JSONException: autoType is not support.错,在FastJsonRedisSerializer类中加入
static {
ParserConfig.getGlobalInstance().addAccept("com.xxxx.blog"); //com.xxxx.blog换成自己的包名..........
}
即可解决
三·代码
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
-
*/
-
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
-
-
public static final Charset DEFAULT_CHARSET = Charset.forName( "UTF-8");
-
-
private Class<T> clazz;
-
-
public FastJsonRedisSerializer(Class<T> clazz) {
-
super();
-
this.clazz = clazz;
-
}
-
-
-
public byte[] serialize(T t) throws SerializationException {
-
if (t == null) {
-
return new byte[ 0];
-
}
-
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
-
}
-
-
-
public T deserialize(byte[] bytes) throws SerializationException {
-
if (bytes == null || bytes.length <= 0) {
-
return null;
-
}
-
String str = new String(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
-
*/
-
-
-
public class RedisConfig extends CachingConfigurerSupport {
-
/**
-
* 设置 redis 数据默认过期时间
-
* 设置@cacheable 序列化方式
-
* @return
-
*/
-
-
public RedisCacheConfiguration redisCacheConfiguration(){
-
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
-
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
-
configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofDays( 30));
-
return configuration;
-
}
-
}
-