redis 反序列化deserialize异常问题解决

在Spring中,RedisTemplate使用JdkSerializationRedisSerializer导致反序列化时出现错误。IncrBy操作由于Redis直接返回Long,不会出错,但'get'操作会触发错误的反序列化过程。解决方案是在spring-redis.xml配置文件中设置RedisTemplate的ValueSerializer为GenericToStringSerializer,以避免类似xacxedx00x05tx00x10这样的前缀问题。
摘要由CSDN通过智能技术生成

日志如下

org.springframework.data.redis.serializer.SerializationException: Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer?; nested exception is java.io.StreamCorruptedException: invalid stream header: 4D797371
    at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer<
  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
Redis的官方未提供Hessian序列化反序列化模块,但可以通过使用开源的Java Hessian库实现Hessian序列化与反序列化。使用步骤如下: 1. 下载Java Hessian库,将jar包添加到Java项目的classpath中。 2. 创建Hessian序列化工具类,将对象序列化成字节数组: ``` import com.caucho.hessian.io.HessianInput; import com.caucho.hessian.io.HessianOutput; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class HessianSerializer { public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); HessianOutput output = new HessianOutput(baos); output.writeObject(obj); return baos.toByteArray(); } public static Object deserialize(byte[] bytes) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); HessianInput input = new HessianInput(bais); return input.readObject(); } } ``` 3. 在Redis中设置Hessian序列化: ``` import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; public class HessianRedisSerializer implements RedisSerializer<Object> { @Override public byte[] serialize(Object obj) throws SerializationException { if (obj == null) { return new byte[0]; } try { return HessianSerializer.serialize(obj); } catch (IOException e) { throw new SerializationException("Hessian serialize error", e); } } @Override public Object deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length == 0) { return null; } try { return HessianSerializer.deserialize(bytes); } catch (IOException e) { throw new SerializationException("Hessian deserialize error", e); } } } ``` 4. 在Redis配置文件中设置Hessian序列化: ``` spring.redis.serializer=com.example.redisserializer.HessianRedisSerializer ``` 以上就是Redis实现Hessian序列化反序列化的简单实现方式。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Think_Higher

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值