记一次Springboot Redis Json序列化失败异常

本文探讨了在SpringBoot应用中,使用FastJson2JsonRedisSerializer进行Redis数据序列化时遇到的问题。当直接插入非序列化的String类型到Redis并尝试通过RedisTemplate获取时,会引发JSON解析错误。解决方案是在Lua脚本中确保数据经过JSON.toJSONString()转换,以保证正确序列化。此问题突显了在微服务架构中数据序列化一致性的重要性。

springboot中配置了FastJson2JsonRedisSerializer

@Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(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);
    }

RedisTemplate会在插入和取值时用FastJson序列化和反序列化,

而我在往Redis中插值时使用了Lua脚本,插入了一个String类型,这个String类型没有用JSON.toJSONString()转换,然后在取值方法里用了默认的RedisTemplate.opsForZSet.range去取值,就出现了序列化问题。报错:

redis com.alibaba.fastjson.JSONException: syntax error, pos 1, line 1, column 2

然后在Lua脚本执行方法把member套个JSON.toJSONString()就没问题了。

### Spring Boot 整合 Redis 序列化问题解决方案 当遇到 Spring BootRedis序列化失败问题时,可以考虑采用高效的序列化库来优化性能并解决问题。以下是几种可能的方案: #### 1. 使用 FlatBuffers 进行高效序列化 FlatBuffers 是一种内存效率高的序列化库,允许访问已序列化的数据而无需解包和解析[^1]。对于需要频繁读取的数据结构尤其有用。 ```java // 定义 FlatBuffer 构建器 FlatBufferBuilder builder = new FlatBufferBuilder(); // 创建对象实例并写入到缓冲区 int offset = MySchema.CreateMyObject(builder, ...); builder.finish(offset); // 获取字节数组用于存储或传输 byte[] bytes = builder.sizedByteArray(); ``` #### 2. 利用 Kryo 实现快速对象图序列化 Kryo 提供了一种快速且有效的对象图序列化框架,适用于复杂对象之间的转换需求。可以通过配置 `RedisTemplate` 来指定使用 KryoSerializer 处理键值对。 ```xml <!-- application.yml --> spring: redis: template: value-serializer: org.nustaq.serialization.FSTSerializer ``` ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); // 设置序列化工具为 Kryo template.setValueSerializer(new GenericFastJsonRedisSerializer()); return template; } } ``` #### 3. MessagePack 编码提高网络传输效率 MessagePack 是一种紧凑二进制编码格式,在保持良好兼容性的同时减少了通信中的冗余信息量。适合于分布式系统的远程过程调用场景下应用。 ```json { "key": "value", "array": [1, 2, 3], "nested_object": {"foo": "bar"} } ``` ```java @Bean public RedisTemplate<String, byte[]> messagePackRedisTemplate(LettuceConnectionFactory connectionFactory) throws Exception { RedisTemplate<String, byte[]> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); // 使用 MsgpackJackson2Module 解析 JSON 数据 ObjectMapper objectMapper = new ObjectMapper() .registerModule(new MsgpackJackson2Module()); template.setDefaultSerializer(new Jackson2JsonRedisSerializer<>(objectMapper)); return template; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值