UserToken userToken = new UserToken(); userToken.setMobile("176****6708"); List list = Lists.newArrayList(userToken); redisTemplate.opsForValue().set("test",list,5,TimeUnit.MINUTES);
2、使用Jackson2JsonRedisSerializer序列化后的数据形式:
3、使用Jackson2JsonRedisSerializer反序列化时报错
List list2 = (List)redisTemplate.opsForValue().get("test"); list2.forEach(userToken1 -> System.out.println(userToken1.getMobile()));
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.com.baisq.model.UserToken
原因:序列化带泛型的数据时,会以map的结构进行存储,反序列化是不能将map解析成对象。
4、解决方案:序列化存储时,转成JSON字符串
UserToken userToken = new UserToken(); userToken.setMobile("176****6708"); List list = Lists.newArrayList(userToken); redisTemplate.opsForValue().set("test3", JSON.toJSONString(userToken),5,TimeUnit.MINUTES); String list2 = (String)redisTemplate.opsForValue().get("test3"); JSON.parseArray(list2,UserToken.class).forEach(userToken1 -> System.out.println(userToken1.getMobile()));
RedisTemplate template = new RedisTemplate(); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
UserToken userToken = new UserToken(); userToken.setMobile("176****6708"); List list = Lists.newArrayList(userToken); redisTemplate.opsForValue().set("test2",list,5,TimeUnit.MINUTES);
2、使用GenericJackson2JsonRedisSerializer序列化后的数据形式:
3、使用GenericJackson2JsonRedisSerializer可以正常反序列化
List list2 = (List)redisTemplate.opsForValue().get("test2"); list2.forEach(userToken1 -> System.out.println(userToken1.getMobile()));
long start = System.currentTimeMillis(); UserToken userToken = new UserToken(); userToken.setMobile("176****6708"); List list = Lists.newArrayListWithCapacity(100); for (int i = 0; i list2 = JSON.parseArray(data, UserToken.class); long end = System.currentTimeMillis(); long time = end - start;