Redis之RedisTemplate配置方式(序列和反序列化)
RedisTemplate配置序列和反序列化
對(duì)于redis操作,springboot進(jìn)行了很好的封裝,那就是spring data redis。提供了一個(gè)高度封裝的RedisTemplate類來(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類通過(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)稍微復(fù)雜?!拘枰猨ackson-mapper-asl工具支持】GenericFastJsonRedisSerializer
:另一種javabean與json之間的轉(zhuǎn)換,同時(shí)也需要指定Class類型。OxmSerializer
:提供了將javabean與xml之間的轉(zhuǎn)換能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存儲(chǔ)的數(shù)據(jù)將是xml工具。不過(guò)使用此策略,編程將會(huì)有些難度,而且效率最低;不建議使用?!拘枰猻pring-oxm模塊的支持】
實(shí)踐
1)依賴(版本繼承了SpringBoot版本)
<dependency> ? ?<groupId>org.springframework.boot</groupId> ? ?<artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2)RedisConfig類
添加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客戶端: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客戶端數(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客戶端數(shù)據(jù)展示
c.不同點(diǎn):
原生redisTemplate操作數(shù)據(jù)序列化方式是和redis配置統(tǒng)一的,redisTemplate回調(diào)函數(shù)操作數(shù)據(jù)序列化方式是自定義的。存值取值是需要注意。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
redis cluster集群模式下實(shí)現(xiàn)批量可重入鎖
本文主要介紹了使用redis cluster集群版所遇到的問(wèn)題解決方案及redis可重入鎖是否會(huì)有死鎖的問(wèn)題等,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02Redis調(diào)用Lua腳本及使用場(chǎng)景快速掌握
Redis?是一種非常流行的內(nèi)存數(shù)據(jù)庫(kù),常用于數(shù)據(jù)緩存與高頻數(shù)據(jù)存儲(chǔ)。大多數(shù)開(kāi)發(fā)人員可能聽(tīng)說(shuō)過(guò)redis可以運(yùn)行?Lua?腳本,但是可能不知道redis在什么情況下需要使用到Lua腳本2022-03-03Redis批量生成數(shù)據(jù)的實(shí)現(xiàn)
本文主要介紹了Redis批量生成數(shù)據(jù)的實(shí)現(xiàn),主要介紹了兩種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06詳解Redis數(shù)據(jù)類型實(shí)現(xiàn)原理
這篇文章主要介紹了Redis數(shù)據(jù)類型實(shí)現(xiàn)原理,在工作中或?qū)W習(xí)中有需要的小伙伴可以參考一下這篇文章2021-08-08Windows安裝Redis并添加本地自啟動(dòng)服務(wù)的實(shí)例詳解
這篇文章主要介紹了Windows安裝Redis并添加本地自啟動(dòng)服務(wù)的實(shí)例詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11