当前位置:网站首页>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
边栏推荐
- 十年開發經驗的程序員告訴你,你還缺少哪些核心競爭力?
- 我服了,MySQL表500W行,居然有人不做分区?
- Micro service practice | introduction and practice of zuul, a micro service gateway
- 洞见云原生|微服务及微服务架构浅析
- ClassFile - Attributes - Code
- What is the future value of fluorite mine of karaqin Xinbao Mining Co., Ltd. under zhongang mining?
- Chrome browser tag management plug-in – onetab
- 【Go实战基础】gin 如何自定义和使用一个中间件
- 机器学习之数据类型案例——基于朴素贝叶斯法,用数据辩男女
- Gocv image cutting and display
猜你喜欢
Matplotlib swordsman line - layout guide and multi map implementation (Updated)
DTM distributed transaction manager PHP collaboration client V0.1 beta release!!!
Chrome browser plug-in fatkun installation and introduction
【Go实战基础】如何安装和使用 gin
Matplotlib swordsman Tour - an artist tutorial to accommodate all rivers
Troubleshooting and handling of an online problem caused by redis zadd
Ora-12514 problem solving method
Programmers with ten years of development experience tell you, what core competitiveness do you lack?
Watermelon book -- Chapter 6 Support vector machine (SVM)
Jd.com interviewer asked: what is the difference between using on or where in the left join association table and conditions
随机推荐
双非本科生进大厂,而我还在底层默默地爬树(上)
View the port of the application published by was
西瓜书--第六章.支持向量机(SVM)
京东面试官问:LEFT JOIN关联表中用ON还是WHERE跟条件有什么区别
告别996,IDEA中必装插件有哪些?
分布式服务架构精讲pdf文档:原理+设计+实战,(收藏再看)
Double non undergraduate students enter the factory, while I am still quietly climbing trees at the bottom (Part 1)
破茧|一文说透什么是真正的云原生
Win10 uses docker to pull the redis image and reports an error read only file system: unknown
Gocv boundary fill
一篇详解带你再次重现《统计学习方法》——第二章、感知机模型
长篇总结(代码有注释)数构(C语言)——第四章、串(上)
hystrix 实现请求合并
Leetcode sword finger offer brush questions - day 23
C language - Blue Bridge Cup - 7 segment code
Number structure (C language -- code with comments) -- Chapter 2, linear table (updated version)
AMQ 4043 solution for errors when using IBM MQ remote connection
Statistical learning methods - Chapter 5, decision tree model and learning (Part 1)
[staff] time sign and note duration (full note | half note | quarter note | eighth note | sixteenth note | thirty second note)
MySql报错:unblock with mysqladmin flush-hosts