日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Redis之RedisTemplate配置方式(序列和反序列化)_Redis

作者:追到烏云的盡頭找太陽(yáng) ? 更新時(shí)間: 2022-05-11 編程語(yǔ)言

RedisTemplate配置序列和反序列化

對(duì)于redis操作,springboot進(jìn)行了很好的封裝,那就是spring data redis。提供了一個(gè)高度封裝的RedisTemplate類(lèi)來(lái)進(jìn)行一系列redis操作,連接池自動(dòng)管理;同時(shí)將事務(wù)封裝操作,交由容器進(jìn)行處理。

針對(duì)數(shù)據(jù)的“序列化和反序列化”,提供了多種策略(RedisSerializer)

默認(rèn)為使用JdkSerializationRedisSerializer,同時(shí)還有StringRedisSerializer,JacksonJsonRedisSerializer,OxmSerializer,GenericFastJsonRedisSerializer。

簡(jiǎn)介一下

  • JdkSerializationRedisSerializer:POJO對(duì)象的存取場(chǎng)景,使用JDK本身序列化機(jī)制,將pojo類(lèi)通過(guò)ObjectInputStream/ObjectOutputStream進(jìn)行序列化操作,最終redis-server中將存儲(chǔ)字節(jié)序列。是目前默認(rèn)的序列化策略。
  • StringRedisSerializer:Key或者value為字符串的場(chǎng)景,根據(jù)指定的charset對(duì)數(shù)據(jù)的字節(jié)序列編碼成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封裝。是最輕量級(jí)和高效的策略。
  • JacksonJsonRedisSerializer:jackson-json工具提供了javabean與json之間的轉(zhuǎn)換能力,可以將pojo實(shí)例序列化成json格式存儲(chǔ)在redis中,也可以將json格式的數(shù)據(jù)轉(zhuǎn)換成pojo實(shí)例。因?yàn)閖ackson工具在序列化和反序列化時(shí),需要明確指定Class類(lèi)型,因此此策略封裝起來(lái)稍微復(fù)雜。【需要jackson-mapper-asl工具支持】
  • GenericFastJsonRedisSerializer:另一種javabean與json之間的轉(zhuǎn)換,同時(shí)也需要指定Class類(lèi)型。
  • OxmSerializer:提供了將javabean與xml之間的轉(zhuǎn)換能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存儲(chǔ)的數(shù)據(jù)將是xml工具。不過(guò)使用此策略,編程將會(huì)有些難度,而且效率最低;不建議使用?!拘枰猻pring-oxm模塊的支持】

實(shí)踐

1)依賴(lài)(版本繼承了SpringBoot版本)


? ?org.springframework.boot
? ?spring-boot-starter-data-redis

2)RedisConfig類(lèi)

添加bean,指定key/value以及HashKey和HashValue的序列化和反序列化為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配置
?* @author 追到烏云的盡頭找太陽(yáng)(Jacob)
?**/
@Configuration
public class RedisConfig {
? ? @Bean
? ? public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
? ? ? ? RedisTemplate redisTemplate = new RedisTemplate<>();
? ? ? ? redisTemplate.setConnectionFactory(redisConnectionFactory);
? ? ? ? // 使用 GenericFastJsonRedisSerializer 替換默認(rèn)序列化
? ? ? ? GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
? ? ? ? // 設(shè)置key和value的序列化規(guī)則
? ? ? ? redisTemplate.setKeySerializer(new GenericToStringSerializer<>(Object.class));
? ? ? ? redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
? ? ? ? // 設(shè)置hashKey和hashValue的序列化規(guī)則
? ? ? ? redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
? ? ? ? redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);
? ? ? ? // 設(shè)置支持事物
? ? ? ? redisTemplate.setEnableTransactionSupport(true);
? ? ? ? redisTemplate.afterPropertiesSet();
? ? ? ? return redisTemplate;
? ? }
}

RedisTemplate序列化問(wèn)題

序列化與反序列化規(guī)則不一致,導(dǎo)致報(bào)錯(cuò)

1、配置redisTemplate


    
        
        
        
        
        
        
        
        
    

    
        
        
        
        
        

        
        
        
        
        
        
        
        
    

    
        
        
            
        
        
            
        
        
            
        
        
            
        
    

2、存值

此次存值,使用redisTemplate的回調(diào)函數(shù),是按照字符串序列化方式存redisValue

?? ?public void testRedisListPush() {
? ? ? ? String redisKey = "testGoodsKey";
? ? ? ? List redisValues = Arrays.asList("10002001", "10002002");
? ? ? ? // 使用管道向redis list結(jié)構(gòu)中批量插入元素
? ? ? ? redisTemplate.executePipelined((RedisConnection redisConnection) -> {
? ? ? ? ? ? // 打開(kāi)管道
? ? ? ? ? ? redisConnection.openPipeline();
? ? ? ? ? ? // 給本次管道內(nèi)添加,一次性執(zhí)行的多條命令
? ? ? ? ? ? for (String redisValue : redisValues) {
? ? ? ? ? ? ? ? redisConnection.rPush(redisKey.getBytes(), redisValue.getBytes());
? ? ? ? ? ? }
? ? ? ? ? ? return null;
? ? ? ? });
? ? }

redis客戶(hù)端:value是字符串

3、取值

此次取值,返回結(jié)果默認(rèn)是按照 1、配置redisTemplate中配置的JdkSerializationRedisSerializer序列化方式,由于存和取的序列化方式不統(tǒng)一,會(huì)產(chǎn)生報(bào)錯(cuò)情況。

	public void testRedisListPop() {
        String redisKey = "testGoodsKey";
        // 使用管道從redis list結(jié)構(gòu)中批量獲取元素
        List objects = redisTemplate.executePipelined((RedisConnection redisConnection) -> {
            // 打開(kāi)管道
            redisConnection.openPipeline();
            for (int i = 0; i < 2; i++) {
                redisConnection.rPop(redisKey.getBytes());
            }
            return null;
        });
        System.out.println(objects);
    }

報(bào)錯(cuò)詳情:反序列化失敗


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入?yún)⒅性偌右粋€(gè)參數(shù):redisTemplate.getStringSerializer(),取值成功,解決問(wèn)題?。?/p>

?? ?public void testRedisListPop() {
? ? ? ? String redisKey = "testGoodsKey";
? ? ? ? // 使用管道從redis list結(jié)構(gòu)中批量獲取元素
? ? ? ? List objects = redisTemplate.executePipelined((RedisConnection redisConnection) -> {
? ? ? ? ? ? // 打開(kāi)管道
? ? ? ? ? ? redisConnection.openPipeline();
? ? ? ? ? ? for (int i = 0; i < 2; i++) {
? ? ? ? ? ? ? ? redisConnection.rPop(redisKey.getBytes());
? ? ? ? ? ? }
? ? ? ? ? ? return null;
? ? ? ? }, redisTemplate.getStringSerializer());
? ? ? ? System.out.println(objects);
? ? }

總結(jié)

1、使用原生redisTemplate操作數(shù)據(jù)和redisTemplate回調(diào)函數(shù)操作數(shù)據(jù)注意點(diǎn):

a.原生redisTemplate操作數(shù)據(jù)

代碼

?? ?public void testRedisListPush() {
? ? ? ? String redisKey = "testGoodsKey";
? ? ? ? List redisValues = Arrays.asList("10002001", "10002002");
? ? ? ? redisValues.forEach(redisValue -> redisTemplate.opsForList().rightPush(redisKey, redisValue));
? ? }

redis客戶(hù)端數(shù)據(jù)展示

b.redisTemplate回調(diào)函數(shù)操作數(shù)據(jù)

代碼

?? ?public void testRedisListPush() {
? ? ? ? String redisKey = "testGoodsKey";
? ? ? ? List redisValues = Arrays.asList("10002001", "10002002");
? ? ? ? // 使用管道向redis list結(jié)構(gòu)中批量插入元素
? ? ? ? redisTemplate.executePipelined((RedisConnection redisConnection) -> {
? ? ? ? ? ? // 打開(kāi)管道
? ? ? ? ? ? redisConnection.openPipeline();
? ? ? ? ? ? // 給本次管道內(nèi)添加,一次性執(zhí)行的多條命令
? ? ? ? ? ? for (String redisValue : redisValues) {
? ? ? ? ? ? ? ? redisConnection.rPush(redisKey.getBytes(), redisValue.getBytes());
? ? ? ? ? ? }
? ? ? ? ? ? return null;
? ? ? ? });
? ? }

redis客戶(hù)端數(shù)據(jù)展示

c.不同點(diǎn):

原生redisTemplate操作數(shù)據(jù)序列化方式是和redis配置統(tǒng)一的,redisTemplate回調(diào)函數(shù)操作數(shù)據(jù)序列化方式是自定義的。存值取值是需要注意。

原文鏈接:https://blog.csdn.net/chen15369337607/article/details/104058934