Redis之RedisTemplate配置方式(序列和反序列化)
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ù)雜?!拘枰猨ackson-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ì)有些難度,而且效率最低;不建議使用。【需要spring-oxm模塊的支持】
實(shí)踐
1)依賴(lài)(版本繼承了SpringBoot版本)
<dependency> ? ?<groupId>org.springframework.boot</groupId> ? ?<artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
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<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { ? ? ? ? RedisTemplate<Object, Object> 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
<!-- redis數(shù)據(jù)源 --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- 最大空閑數(shù) --> <property name="maxIdle" value="${redis.maxIdle}"/> <!-- 最大空連接數(shù) --> <property name="maxTotal" value="${redis.maxTotal}"/> <!-- 最大等待時(shí)間 --> <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/> <!-- 返回連接時(shí),檢測(cè)連接是否成功 --> <property name="testOnBorrow" value="${redis.testOnBorrow}"/> </bean> <!-- Spring-data-redis連接池管理工廠 --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <!-- IP地址 --> <property name="hostName" value="${redis.host}"/> <!-- 端口號(hào) --> <property name="port" value="${redis.port}"/> <!-- 密碼 --> <!-- <property name="password" value="${redis.password}"/>--> <!-- 超時(shí)時(shí)間 默認(rèn)2000 --> <property name="timeout" value="${redis.timeout}"/> <!-- 連接池配置引用 --> <property name="poolConfig" ref="poolConfig"/> <!-- 是否使用連接池 --> <property name="usePool" value="true"/> <!-- 指定使用的數(shù)據(jù)庫(kù) --> <property name="database" value="0"/> </bean> <!-- redis template definition --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"/> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> </bean>
2、存值
此次存值,使用redisTemplate的回調(diào)函數(shù),是按照字符串序列化方式存redisValue
?? ?public void testRedisListPush() { ? ? ? ? String redisKey = "testGoodsKey"; ? ? ? ? List<String> 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<Object> 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.<init>(ObjectInputStream.java:357)
at org.springframework.core.ConfigurableObjectInputStream.<init>(ConfigurableObjectInputStream.java:63)
at org.springframework.core.ConfigurableObjectInputStream.<init>(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<Object> 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<String> 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<String> 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ù)序列化方式是自定義的。存值取值是需要注意。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- RedisTemplate默認(rèn)序列化方式顯示中文亂碼的解決
- RedisTemplate序列化設(shè)置的流程和具體步驟
- redis redistemplate序列化對(duì)象配置方式
- 配置redis的序列化,注入RedisTemplate方式
- Spring?boot?RedisTemplate?序列化服務(wù)化配置方式
- Springboot下RedisTemplate的兩種序列化方式實(shí)例詳解
- Springboot?引入?Redis?并配置序列化并封裝RedisTemplate?
- 解決RedisTemplate的key默認(rèn)序列化器的問(wèn)題
- Spring的RedisTemplate的json反序列泛型丟失問(wèn)題解決
相關(guān)文章
Redis之SDS數(shù)據(jù)結(jié)構(gòu)的使用
本文主要介紹了Redis之SDS數(shù)據(jù)結(jié)構(gòu)的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08Redis使用SETNX命令實(shí)現(xiàn)分布式鎖
分布式鎖是一種用于在分布式系統(tǒng)中控制多個(gè)節(jié)點(diǎn)對(duì)共享資源進(jìn)行訪問(wèn)的機(jī)制,本文主要為大家詳細(xì)介紹了Redis如何使用SETNX命令實(shí)現(xiàn)分布式鎖,需要的可以參考下2025-01-01Redis 數(shù)據(jù)遷移的項(xiàng)目實(shí)踐
本文主要介紹了Redis 數(shù)據(jù)遷移的項(xiàng)目實(shí)踐,通過(guò)Redis-shake的sync(同步)模式,可以將Redis的數(shù)據(jù)實(shí)時(shí)遷移至另一套R(shí)edis環(huán)境,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09深入理解Redis內(nèi)存回收和內(nèi)存淘汰機(jī)制
Redis使用多種過(guò)期策略和內(nèi)存淘汰機(jī)制來(lái)管理內(nèi)存,本文主要介紹了深入理解Redis內(nèi)存回收和內(nèi)存淘汰機(jī)制, 具有一定的參考價(jià)值,感興趣的可以了解一下2024-06-06詳解Redis用鏈表實(shí)現(xiàn)消息隊(duì)列
Redis有兩種方式實(shí)現(xiàn)消息隊(duì)列,一種是用Redis自帶的鏈表數(shù)據(jù)結(jié)構(gòu),另一種是用Redis發(fā)布/訂閱模式實(shí)現(xiàn),這篇文章先介紹鏈表實(shí)現(xiàn)消息隊(duì)列,有需要的朋友們可以參考借鑒。2016-09-09