springboot redis fastjson
@Configuration
public class RedisConfig {
@Bean
public RedisTemplateredisTemplate(RedisConnectionFactory factory, RedisSerializer fastJson2JsonRedisSerializer) {
RedisTemplate redisTemplate =new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
//key采用String序列化方式;但是如果方法上有Long等非String类型的话,会报类型转换错误;
StringRedisSerializer stringRedisSerializer =new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
//value采用fast-json序列化方式。
redisTemplate.setValueSerializer(fastJson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public RedisSerializerfastJson2JsonRedisSerializer() {
return new FastJson2JsonRedisSerializer<>(Object.class);
}
public static class FastJson2JsonRedisSerializerimplements RedisSerializer {
public static final CharsetDEFAULT_CHARSET = StandardCharsets.UTF_8;
private Classclazz;
public FastJson2JsonRedisSerializer(Class 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, Feature.SupportAutoType);
}
}
}