【springboot】2.0配置@cacheable⾃定义序列化⽅式缓存数据到redis 转⾃ blog.csdn/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 {
}
即可解决
三·代码
1·⾃定义序列化⽅式
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.dis.serializer.RedisSerializer;
import org.dis.serializer.SerializationException;
import java.nio.charset.Charset;
/**
* 说明:⾃定义redis序列化⽅式fastjson常用方法
*
* @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;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[ 0];
}
JSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
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 t.annotation.Bean;
import t.annotation.Configuration;
import org.dis.cache.RedisCacheConfiguration;
import org.dis.serializer.RedisSerializationContext;
import java.time.Duration;
/**
*
* @author WangBin
* @version V1.0
* @date 2017.12.05
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* 设置 redis 数据默认过期时间
* 设置@cacheable 序列化⽅式
* @return
*/
@Bean
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;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论