In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to configure sequence and deserialization in Redis". In daily operation, I believe that many people have doubts about how to configure sequence and deserialization in Redis. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the question of "how to configure sequence and deserialization in Redis". Next, please follow the editor to study!
RedisTemplate configuration sequence and deserialization
For redis operations, springboot is well encapsulated, and that is spring data redis. A highly encapsulated RedisTemplate class is provided to perform a series of redis operations and the connection pool is managed automatically; at the same time, the transaction is encapsulated and handed over to the container for processing.
Multiple strategies (RedisSerializer) are provided for "serialization and deserialization" of data
The default is to use JdkSerializationRedisSerializer, along with StringRedisSerializer,JacksonJsonRedisSerializer,OxmSerializer,GenericFastJsonRedisSerializer.
Give a brief introduction
In the access scenario of JdkSerializationRedisSerializer:POJO object, using the serialization mechanism of JDK itself, the pojo class is serialized through ObjectInputStream/ObjectOutputStream, and the byte sequence will be stored in redis-server finally. Is currently the default serialization policy.
When StringRedisSerializer:Key or value is a string, the byte sequence of the data is encoded into string according to the specified charset, which is the direct encapsulation of "new String (bytes, charset)" and "string.getBytes (charset)". Is the most lightweight and efficient strategy.
The JacksonJsonRedisSerializer:jackson-json tool provides the conversion ability between javabean and json, which can serialize pojo instances into json format and store them in redis, or convert data in json format into pojo instances. Because the jackson tool needs to specify the Class type explicitly when serializing and deserializing, this policy is slightly more complex to encapsulate. [jackson-mapper-asl tool support required]
GenericFastJsonRedisSerializer: another conversion between javabean and json, and you also need to specify the Class type.
OxmSerializer: provides the ability to convert javabean to xml, and the currently available tripartite support, including jaxb,apache-xmlbeans;redis stored data, will be xml tools. However, using this strategy, programming will be somewhat difficult and least efficient; it is not recommended. [support of spring-oxm module is required]
Practice
1) dependency (the version inherits the SpringBoot version)
Org.springframework.boot spring-boot-starter-data-redis
2) RedisConfig class
Add bean, specifying key/value and serialization and deserialization of HashKey and HashValue to FastJson.
Package com.sleb.springcloud.common.config;import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.GenericToStringSerializer / * * redis configuration * @ author chase to the end of the dark cloud to find the sun (Jacob) / @ Configurationpublic class RedisConfig {@ Bean public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) {RedisTemplate redisTemplate = new RedisTemplate (); redisTemplate.setConnectionFactory (redisConnectionFactory); / / use GenericFastJsonRedisSerializer to replace the default serialization GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer () / / set serialization rules for key and value redisTemplate.setKeySerializer (new GenericToStringSerializer (Object.class)); redisTemplate.setValueSerializer (genericFastJsonRedisSerializer); / / set serialization rules redisTemplate.setHashKeySerializer (new GenericToStringSerializer (Object.class)) for hashKey and hashValue; redisTemplate.setHashValueSerializer (genericFastJsonRedisSerializer); / / set redisTemplate.setEnableTransactionSupport (true) for supporting things; redisTemplate.afterPropertiesSet () Return redisTemplate;}} RedisTemplate serialization problem Serialization and deserialization rules are inconsistent, resulting in error problem
1. Configure redisTemplate
2. Stored value
The stored value, using the callback function of redisTemplate, is to store redisValue according to string serialization.
Public void testRedisListPush () {String redisKey = "testGoodsKey"; List redisValues = Arrays.asList ("10002001", "10002002"); / / use pipes to bulk insert elements redisTemplate.executePipelined ((RedisConnection redisConnection)-> {/ / open pipe redisConnection.openPipeline ()) into the redis list structure / / add multiple commands for (String redisValue: redisValues) {redisConnection.rPush (redisKey.getBytes (), redisValue.getBytes ();} return null;}) to this pipeline and execute them at one time;}
Redis client: value is a string
3. Value
For this value, the returned result defaults to the JdkSerializationRedisSerializer serialization method configured in configuration redisTemplate. Due to the different serialization methods of storage and fetching, an error will occur.
Public void testRedisListPop () {String redisKey = "testGoodsKey"; / / use pipes to batch get elements List objects = redisTemplate.executePipelined ((RedisConnection redisConnection)-> {/ / Open pipe redisConnection.openPipeline (); for (int I = 0; I) from the redis list structure
< 2; i++) { redisConnection.rPop(redisKey.getBytes()); } return null; }); System.out.println(objects); } 报错详情:反序列化失败 org.springframework.data.redis.serializer.SerializationException: Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer?; nested exception is java.io.StreamCorruptedException: invalid stream header: 31303030 ... Caused by: org.springframework.core.serializer.support.SerializationFailedException: Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer?; nested exception is java.io.StreamCorruptedException: invalid stream header: 31303030 at org.springframework.core.serializer.support.DeserializingConverter.convert(DeserializingConverter.java:78) at org.springframework.core.serializer.support.DeserializingConverter.convert(DeserializingConverter.java:36) at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.deserialize(JdkSerializationRedisSerializer.java:80) ... 39 more Caused by: java.io.StreamCorruptedException: invalid stream header: 31303030 at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:899) at java.io.ObjectInputStream.(ObjectInputStream.java:357) at org.springframework.core.ConfigurableObjectInputStream.(ConfigurableObjectInputStream.java:63) at org.springframework.core.ConfigurableObjectInputStream.(ConfigurableObjectInputStream.java:49) at org.springframework.core.serializer.DefaultDeserializer.deserialize(DefaultDeserializer.java:68) at org.springframework.core.serializer.support.DeserializingConverter.convert(DeserializingConverter.java:73) ... 41 more 解决办法 1、取值 需要在redisTemplate.executePipelined入参中再加一个参数:redisTemplate.getStringSerializer(),取值成功,解决问题!! public void testRedisListPop() { String redisKey = "testGoodsKey"; // 使用管道从redis list结构中批量获取元素 List objects = redisTemplate.executePipelined((RedisConnection redisConnection) ->{/ / Open pipe redisConnection.openPipeline (); for (int I = 0; I
< 2; i++) { redisConnection.rPop(redisKey.getBytes()); } return null; }, redisTemplate.getStringSerializer()); System.out.println(objects); }总结 1、使用原生redisTemplate操作数据和redisTemplate回调函数操作数据注意点: a.原生redisTemplate操作数据 代码 public void testRedisListPush() { String redisKey = "testGoodsKey"; List redisValues = Arrays.asList("10002001", "10002002"); redisValues.forEach(redisValue ->RedisTemplate.opsForList () .rightPush (redisKey, redisValue);}
Redis client data presentation
B.redisTemplate callback function operation data
Code
Public void testRedisListPush () {String redisKey = "testGoodsKey"; List redisValues = Arrays.asList ("10002001", "10002002"); / / use pipes to bulk insert elements redisTemplate.executePipelined ((RedisConnection redisConnection)-> {/ / open pipe redisConnection.openPipeline ()) into the redis list structure / / add multiple commands for (String redisValue: redisValues) {redisConnection.rPush (redisKey.getBytes (), redisValue.getBytes ();} return null;}) to this pipeline and execute them at one time;}
Redis client data presentation
c. Differences:
The serialization method of native redisTemplate operation data is the same as that of redis configuration, and the redisTemplate callback function operates in a custom way. The value of the stored value needs to be paid attention to.
At this point, the study on "how to configure sequence and deserialization of RedisTemplate in Redis" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.