redis使⽤fastjson序列化和反序列化redis
class FastJson2JsonRedisSerializer<T>implements RedisSerializer<T>{
private ObjectMapper objectMapper =new ObjectMapper();
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
static{
}
public FastJson2JsonRedisSerializer(Class<T> clazz){
super();
fastjson怎么用
this.clazz = clazz;
}
public byte[]serialize(T t)throws SerializationException {
if(t == null){
return new byte[0];
}
JSONString(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);
}
public void setObjectMapper(ObjectMapper objectMapper){
this.objectMapper = objectMapper;
}
protected JavaType getJavaType(Class<?> clazz){
return TypeFactory.defaultInstance().constructType(clazz);
}
}
redisconfig
/**
* @Classname: com.openailab.figuration.RedisConfig
* @Description: Redis配置类
* @Author: zxzhang
* @Date: 2019/7/1
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object>redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String, Object> redisTemplate =new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
FastJson2JsonRedisSerializer fastJson2JsonRedisSerializer =new FastJson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper =new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
fastJson2JsonRedisSerializer.setObjectMapper(objectMapper);
StringRedisSerializer stringRedisSerializer =new StringRedisSerializer();
// key采⽤String的序列化⽅式
redisTemplate.setKeySerializer(stringRedisSerializer);
// string的value采⽤fastJson序列化⽅式
redisTemplate.setValueSerializer(fastJson2JsonRedisSerializer);
// hash的key也采⽤String的序列化⽅式
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// hash的value采⽤fastJson序列化⽅式
redisTemplate.setHashValueSerializer(fastJson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论