当前位置:网站首页>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
边栏推荐
- From concept to method, the statistical learning method -- Chapter 3, k-nearest neighbor method
- Actual combat of microservices | discovery and invocation of original ecosystem implementation services
- 概念到方法,绝了《统计学习方法》——第三章、k近邻法
- Elastic Stack之Beats(Filebeat、Metricbeat)、Kibana、Logstash教程
- 队列管理器running状态下无法查看通道
- 2022/2/14 summary
- CSDN Q & A_ Evaluation
- In depth analysis of how the JVM executes Hello World
- Statistical learning methods - Chapter 5, decision tree model and learning (Part 1)
- 西瓜书--第五章.神经网络
猜你喜欢
Insight into cloud native | microservices and microservice architecture
ORA-12514问题解决方法
C language implementation of mine sweeping game
Multi version concurrency control mvcc of MySQL
十年开发经验的程序员告诉你,你还缺少哪些核心竞争力?
【Go实战基础】gin 高效神器,如何将参数绑定到结构体
The channel cannot be viewed when the queue manager is running
Number structure (C language -- code with comments) -- Chapter 2, linear table (updated version)
Dix ans d'expérience dans le développement de programmeurs vous disent quelles compétences de base vous manquez encore?
【Go实战基础】gin 如何设置路由
随机推荐
概念到方法,绝了《统计学习方法》——第三章、k近邻法
Chrome video download Plug-in – video downloader for Chrome
Machine learning practice: is Mermaid a love movie or an action movie? KNN announces the answer
破茧|一文说透什么是真正的云原生
Cloudrev self built cloud disk practice, I said that no one can limit my capacity and speed
Microservice practice | load balancing component and source code analysis
win10使用docker拉取redis镜像报错read-only file system: unknown
Matplotlib剑客行——没有工具用代码也能画图的造型师
A detailed explanation takes you to reproduce the statistical learning method again -- Chapter 2, perceptron model
Who is better for Beijing software development? How to find someone to develop system software
I've taken it. MySQL table 500W rows, but someone doesn't partition it?
Pyspark de duplication dropduplicates, distinct; withColumn、lit、col; unionByName、groupBy
AMQ6126问题解决思路
别找了,Chrome浏览器必装插件都在这了
C language implementation of mine sweeping game
Chrome browser tag management plug-in – onetab
C4D quick start tutorial - Chamfer
「面试高频题」难度大 1.5/5,经典「前缀和 + 二分」运用题
Leetcode sword finger offer brush questions - day 22
JVM指令助记符