67,513
社区成员
发帖
与我相关
我的任务
分享
/**
* 重写序列化 序列化为字节码
*
* @author hyp
*/
public class MyRedisSerializer implements RedisSerializer<Object> {
@Override
public byte[] serialize(Object o) throws SerializationException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream objOut;
try {
objOut = new ObjectOutputStream(byteOut);
objOut.writeObject(o);
} catch (IOException e) {
e.printStackTrace();
}
return byteOut.toByteArray();
}
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
if (bytes == null) {
return null;
}
ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
ObjectInputStream objIn;
Object obj;
try {
objIn = new ObjectInputStream(byteIn);
obj = objIn.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return obj;
}
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
MyRedisSerializer myRedisSerializer = new MyRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(myRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(myRedisSerializer);
template.afterPropertiesSet();
return template;
}