当前位置:网站首页>Difference between redis serialization genericjackson2jsonredisserializer and jackson2jsonredisserializer
Difference between redis serialization genericjackson2jsonredisserializer and jackson2jsonredisserializer
2022-07-02 09:22:00 【Protect our fat tiger】
List of articles
/** * Instantiation RedisTemplate object * @return */
@Bean
public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key All use String Serialization mode
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
// Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
GenericJackson2JsonRedisSerializer
GenericJackson2JsonRedisSerializer Serialization , The fully qualified name of the serialized object will be saved , from redis When obtaining data, it can be directly de sequenced into the specified object
General parameters are as follows :
List<Student> students = new ArrayList<>();
Student xm = new Student(" Xiao Ming ", 12);
Student ph = new Student(" Fat tiger ", 12);
students.add(xm);
students.add(ph);
(1)VALUE Save common objects
save :
Student xm = new Student(" Xiao Ming ", 12);
redisTemplate.opsForValue().set(xm.getName(), xm);

Value is accompanied by entity information
take :
Student xmCache = (Student)redisTemplate.opsForValue().get(xm.getName());
// Student(name= Xiao Ming , age=12)
System.out.println(xmCache);
Conclusion :GenericJackson2JsonRedisSerializer Serialization mode It can be stored directly VALUE As object , And from Redis Get strong conversion
(2)VALUE Save object collection
save :
redisTemplate.opsForSet().add("students-genericJackson2JsonRedisSerializer", students);
redisTemplate.opsForValue().set("students-str", students);

Values contain both fully qualified names of entity classes and collection types
–

The fully qualified name of the entity class is carried in the concrete value
take :
List<Student> studentCache = (List<Student>) redisTemplate.opsForValue().get("students-str");
Set<Object> members = redisTemplate.opsForSet().members("students-genericJackson2JsonRedisSerializer");
// [Student(name= Xiao Ming , age=12), Student(name= Fat tiger , age=12)]
System.out.println(studentCache);
// [Student(name= Fat tiger , age=12), Student(name= Xiao Ming , age=12)]
System.out.println(members);
Conclusion :GenericJackson2JsonRedisSerializer Serialization mode It can be stored directly VALUE Set objects , And from Redis Get strong conversion
(3)VALUE save JSON character string
redisTemplate.opsForValue().set(ph.getName(), JSON.toJSONString(ph));
save :

nothing @class Field , And jSON The string contains escape characters
take :
Object o = redisTemplate.opsForValue().get(ph.getName());
System.out.println(o);

Be careful : Because here is JSON character string , So when retrieving data , Nor can it be directly forced to Student object , We need to call the method manually , take JSON String conversion to JAVA object
redisTemplate.opsForValue().set(ph.getName(), JSON.toJSONString(ph));
Object o = redisTemplate.opsForValue().get(ph.getName());
// Student(name= Fat tiger , age=12)
System.out.println(o == null ? null : JSON.parseObject(o.toString(), Student.class));
Conclusion :GenericJackson2JsonRedisSerializer Serialization mode It can be stored directly VALUE by JSON String form , And from Redis No forced conversion is allowed after obtaining , You need to convert the result into a string , then JSON The string is converted to the object or collection of objects you need
(4) The Conduit Pipelined Save the data
save :
List<Student> students = new ArrayList<>();
Student xm = new Student(" Xiao Ming ", 12); Student ph = new Student(" Fat tiger ", 12);
students.add(xm); students.add(ph);
redisTemplate.executePipelined((RedisCallback) conn -> {
students.forEach(s -> conn.set(s.getName().getBytes(), JSON.toJSONString(s).getBytes()));
return null;
});


The data of pipeline operation does not @class Entity class properties , The fully qualified name of the entity class is missing , Can we still get the data at this time ?
The answer is no
take :
Direct forced rotation after taking :
Student xmCache = (Student)redisTemplate.opsForValue().get(xm.getName());
System.out.println(xmCache);

GET No forced transfer after taking
Object xmCache = redisTemplate.opsForValue().get(xm.getName());
System.out.println(xmCache);

MGET Batch acquisition
List<Object> objectList = redisTemplate.opsForValue().multiGet(students.stream().map(Student::getName).collect(Collectors.toList()));
System.out.println(objectList);
return objectList;

ERROR 16400 — [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Missing type id when trying to resolve subtype of [simple type, class java.lang.Object]: missing type id property ‘@class’
at [Source: (byte[])"{“age”:12,“name”:“ Xiao Ming ”}"; line: 1, column: 26]; nested exception is com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class java.lang.Object]: missing type id property ‘@class’
at [Source: (byte[])"{“age”:12,“name”:“ Xiao Ming ”}"; line: 1, column: 26]] with root cause
The translation means : Can't read JSON: Try to parse [ Simple type , class java.lang.Object] Missing type when subtyped by ID: Missing type id attribute “@class”
Conclusion : Use GenericJackson2JsonRedisSerializer After serialization for pipeline operation , Entity class @class Attributes will be lost , Again from redis Getting data will not be able to deserialize successfully
Jackson2JsonRedisSerializer
General parameters are as follows :
List<Student> students = new ArrayList<>();
Student ys = new Student(" The rope ", 12);
Student mw = new Student(" Tryndamere ", 12);
students.add(ys);
students.add(mw);
(1)VALUE Save common objects
save :
redisTemplate.opsForValue().set(ys.getName(), ys);
redisTemplate.opsForValue().set(mw.getName(), mw);

take :
Student ysCache = (Student)redisTemplate.opsForValue().get(ys.getName());
System.out.println(ysCache);
Found an error :java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.leilei.entity.Student

Breakpoint debugging : Acquired ysCache It's actually a LinkedHashMap
Object ysCache = redisTemplate.opsForValue().get(ys.getName());
System.out.println(ysCache);

Save the object set, and the result is the same …
redisTemplate.opsForValue().set("lol", students);
Object lolCache = redisTemplate.opsForValue().get("lol");
System.out.println(lolCache);

terms of settlement :
Jackson2JsonRedisSerializer Serialization All stored data adopt JSON String mode , Then, when taking data, it does not directly force the result , But use JSON Deserialization take JSON Deserialize string to java Object or collection
See example 2 :VALUE save JSON character string
Conclusion :Jackson2JsonRedisSerializer Serialization mode , Such as VALUE Store objects or collections of objects directly , The result is LinkedHashMap, Cannot be used directly JDK Forcibly convert a method to an object or a collection of objects , It needs tools to convert into entities and entity sets
(2)VALUE save JSON character string
save :
redisTemplate.opsForValue().set(ys.getName(), JSON.toJSONString(ys));
redisTemplate.opsForValue().set(mw.getName(), JSON.toJSONString(mw));

–

There are escape characters in the string
take :
Object ysCache = redisTemplate.opsForValue().get(ys.getName());
// Student(name= The rope , age=122)
System.out.println(ysCache == null ? null : JSON.parseObject(ysCache.toString(), Student.class));
List<Object> cacheList = redisTemplate.opsForValue().multiGet(students.stream().map(Student::getName).collect(Collectors.toList()));
List<Student> studentList = cacheList.stream().filter(Objects::nonNull).map(Object::toString).map(x -> JSON.parseObject(x, Student.class)).collect(Collectors.toList());
// [Student(name= The rope , age=122), Student(name= Tryndamere , age=234)]
System.out.println(studentList);
Conclusion :Jackson2JsonRedisSerializer Serialization mode ,VALUE save JSON When the string , The value is also JSON character string , Need a JSON Tools to convert to entity classes or entity collections
(3) The Conduit Pipelined Save the data
save :
redisTemplate.executePipelined((RedisCallback<String>) conn -> {
students.forEach(s -> conn.set(s.getName().getBytes(), JSON.toJSONString(s).getBytes()));
return null;
});

–

take :
Get the value stored in the pipeline to LinkedHashMap

Because we need to put map To java object , What I use here is to turn first JSON String mode


List<Object> cacheList = redisTemplate.opsForValue().multiGet(students.stream().map(Student::getName).collect(Collectors.toList()));
if (CollectionUtils.isEmpty(cacheList)) {
return null;
}
List<Student> studentList = cacheList.stream().filter(Objects::nonNull).map(JSON::toJSONString).map(x -> JSON.parseObject(x, Student.class)).collect(Collectors.toList());
// [Student(name= The rope , age=122), Student(name= Tryndamere , age=234)]
System.out.println(studentList);
Conclusion :Jackson2JsonRedisSerializer Serialization mode , And after using pipeline operation , The value obtained is also a linkedHashMap, Tools are needed to deserialize values into entity objects or collections of entity objects
边栏推荐
- [go practical basis] how to bind and use URL parameters in gin
- [go practical basis] how to set the route in gin
- [go practical basis] how can gin get the request parameters of get and post
- Matplotlib剑客行——布局指南与多图实现(更新)
- Microservice practice | declarative service invocation openfeign practice
- Redis安装部署(Windows/Linux)
- 别找了,Chrome浏览器必装插件都在这了
- 概率还不会的快看过来《统计学习方法》——第四章、朴素贝叶斯法
- cmd窗口中中文呈现乱码解决方法
- Redis installation and deployment (windows/linux)
猜你喜欢

微服务实战|原生态实现服务的发现与调用

Machine learning practice: is Mermaid a love movie or an action movie? KNN announces the answer

Matplotlib剑客行——初相识Matplotlib

Cloudreve自建云盘实践,我说了没人能限制得了我的容量和速度

远程连接IBM MQ报错AMQ4036解决方法

破茧|一文说透什么是真正的云原生

【Go实战基础】gin 如何获取 GET 和 POST 的请求参数

【Go实战基础】gin 如何绑定与使用 url 参数

C language - Blue Bridge Cup - 7 segment code

西瓜书--第六章.支持向量机(SVM)
随机推荐
深入剖析JVM是如何执行Hello World的
微服务实战|负载均衡组件及源码分析
Long summary (code with comments) number structure (C language) -- Chapter 4, string (Part 1)
View the port of the application published by was
微服务实战|微服务网关Zuul入门与实战
Gocv image reading and display
Chrome browser tag management plug-in – onetab
Dix ans d'expérience dans le développement de programmeurs vous disent quelles compétences de base vous manquez encore?
以字节跳动内部 Data Catalog 架构升级为例聊业务系统的性能优化
Chrome浏览器标签管理插件–OneTab
双非本科生进大厂,而我还在底层默默地爬树(上)
Pdf document of distributed service architecture: principle + Design + practice, (collect and see again)
【Go实战基础】gin 高效神器,如何将参数绑定到结构体
Chrome用户脚本管理器-Tampermonkey 油猴
Chrome视频下载插件–Video Downloader for Chrome
企业级SaaS CRM实现
Say goodbye to 996. What are the necessary plug-ins in idea?
Chrome user script manager tempermonkey monkey
ClassFile - Attributes - Code
AMQ 4043 solution for errors when using IBM MQ remote connection