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()

相关推荐
catino18 分钟前
spring-Bean
java·后端·spring
深入云栈30 分钟前
Netty 4.2.x 源码深度解析 (十一):EventExecutor 业务线程池 —— 防止 IO 线程阻塞的并发模型
java·后端
吴声子夜歌34 分钟前
Java——基本类型
java·开发语言
程序员夏洛2 小时前
Redis 数据过期后的删除策略是什么?
数据库·redis·缓存
鱼鳞_2 小时前
热门八股-Redis
数据库·redis·缓存
CoderYanger2 小时前
A.每日一题:输入单词需要的最少按键次数 Ⅰ+Ⅱ
java·数据结构·算法·leetcode·面试
Cosolar2 小时前
一文弄懂 Agent Harness 与 Agent Runtime 的区别
java·后端·github
吴声子夜歌2 小时前
Java——类、对象及方法(一)
java·开发语言
AIGC小尼2 小时前
2026 最新实战|SpringCloud 微服务整合 SpringAI 完整落地教程(RAG 知识库 + 限流降级 + 跨服务调用)
spring·spring cloud·微服务
程序员夏洛2 小时前
Redis 的持久化机制有哪些?
java·数据库·redis