RedisTemplate 序列化成功,反序列化失败List, Set, Map失败

RedisTemplate 序列化成功,反序列化失败List, Set, Map失败

序列化成功,反序列化失败

异常信息

text 复制代码
Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id '6' as a subtype of `java.lang.Object`: no such class found
 at [Source: (byte[])"[6,7,1,2,3,4,5]"; line: 1, column: 4]
text 复制代码
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected VALUE_STRING: need String, Number of Boolean value that contains type id (for subtype of java.lang.Object)
 at [Source: (byte[])"[

RedisTemplate配置

首先确定RedisTemplate序列化器设置正确

java 复制代码
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
     RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
     redisTemplate.setConnectionFactory(redisConnectionFactory);

     //String的序列化方式
     // 使用GenericJackson2JsonRedisSerializer 替换默认序列化(默认采用的是JDK序列化)

     //序列号key value
     redisTemplate.setKeySerializer(RedisSerializer.string());
     redisTemplate.setValueSerializer(RedisSerializer.json());
     redisTemplate.setHashKeySerializer(RedisSerializer.string());
     redisTemplate.setHashValueSerializer(RedisSerializer.json());

     redisTemplate.afterPropertiesSet();
     return redisTemplate;
 }

异常原因

使用了List.of(), Set.of(), Map.of()等方法导致序列化时没有类型

使用stream api 的 toList 方法

错误代码示例

java 复制代码
 Map<String, List<Integer>> map = new HashMap<>();
 Map<Integer, Integer> map2 = Map.of(1, 2, 3, 4);
 List<Integer> list = List.of(1, 2, 34, 54, 5);
 ArrayList<Integer> arrayList = new ArrayList<>(list);
 map.put("1", list);
 redisTemplate.opsForHash().putAll("test:1", map);
 redisTemplate.opsForHash().put("test:2", "1", arrayList);
 Set<Integer> nums = Set.of(1, 2, 3, 4, 5, 6, 7);
 redisTemplate.opsForValue().set("test:3", nums);

这是错误的序列化,会导致反序列化失败

正确的序列化的带有java类型的

解决方法

不使用List.of(), Set.of(), Map.of() 等静态方法

使用.collect(Collectors.toList())代替stream().toList()

相关推荐
A阳俊yi13 分钟前
Spring Boot日志配置
java·spring boot·后端
苹果酱056713 分钟前
2020-06-23 暑期学习日更计划(机器学习入门之路(资源汇总)+概率论)
java·vue.js·spring boot·mysql·课程设计
echo17542538 分钟前
Apipost免费版、企业版和私有化部署详解
java
大家都说我身材好44 分钟前
Spring缓存注解深度实战:3大核心注解解锁高并发系统性能优化‌
spring·缓存·性能优化
爱吃泡芙的小白白1 小时前
爬虫学习——使用HTTP服务代理、redis使用、通过Scrapy实现分布式爬取
redis·分布式·爬虫·http代理·学习记录
异常君1 小时前
Java 高并发编程:等值判断的隐患与如何精确控制线程状态
java·后端·代码规范
异常君1 小时前
Java 日期处理:SimpleDateFormat 线程安全问题及解决方案
java·后端·代码规范
都叫我大帅哥1 小时前
Spring AI中的ChatClient:从入门到精通,一篇搞定!
java·spring·ai编程
都叫我大帅哥1 小时前
《@SpringBootApplication:Spring Boot的"一键启动"按钮,还是程序员的"免死金牌"?》
java·后端·spring
triticale1 小时前
P12167 [蓝桥杯 2025 省 C/Python A] 倒水
java·蓝桥杯