Redis之RedisTemplate配置方式(序列和反序列化)
RedisTemplate配置序列和反序列化
對于redis操作,springboot進行了很好的封裝,那就是spring data redis。提供了一個高度封裝的RedisTemplate類來進行一系列redis操作,連接池自動管理;同時將事務(wù)封裝操作,交由容器進行處理。
針對數(shù)據(jù)的“序列化和反序列化”,提供了多種策略(RedisSerializer)
默認為使用JdkSerializationRedisSerializer,同時還有StringRedisSerializer,JacksonJsonRedisSerializer,OxmSerializer,GenericFastJsonRedisSerializer。
簡介一下
JdkSerializationRedisSerializer:POJO對象的存取場景,使用JDK本身序列化機制,將pojo類通過ObjectInputStream/ObjectOutputStream進行序列化操作,最終redis-server中將存儲字節(jié)序列。是目前默認的序列化策略。StringRedisSerializer:Key或者value為字符串的場景,根據(jù)指定的charset對數(shù)據(jù)的字節(jié)序列編碼成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封裝。是最輕量級和高效的策略。JacksonJsonRedisSerializer:jackson-json工具提供了javabean與json之間的轉(zhuǎn)換能力,可以將pojo實例序列化成json格式存儲在redis中,也可以將json格式的數(shù)據(jù)轉(zhuǎn)換成pojo實例。因為jackson工具在序列化和反序列化時,需要明確指定Class類型,因此此策略封裝起來稍微復(fù)雜?!拘枰猨ackson-mapper-asl工具支持】GenericFastJsonRedisSerializer:另一種javabean與json之間的轉(zhuǎn)換,同時也需要指定Class類型。OxmSerializer:提供了將javabean與xml之間的轉(zhuǎn)換能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存儲的數(shù)據(jù)將是xml工具。不過使用此策略,編程將會有些難度,而且效率最低;不建議使用?!拘枰猻pring-oxm模塊的支持】
實踐
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 追到烏云的盡頭找太陽(Jacob)
?**/
@Configuration
public class RedisConfig {
? ? @Bean
? ? public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
? ? ? ? RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
? ? ? ? redisTemplate.setConnectionFactory(redisConnectionFactory);
? ? ? ? // 使用 GenericFastJsonRedisSerializer 替換默認序列化
? ? ? ? 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序列化問題
序列化與反序列化規(guī)則不一致,導(dǎo)致報錯
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}"/>
<!-- 最大等待時間 -->
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
<!-- 返回連接時,檢測連接是否成功 -->
<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}"/>
<!-- 端口號 -->
<property name="port" value="${redis.port}"/>
<!-- 密碼 -->
<!-- <property name="password" value="${redis.password}"/>-->
<!-- 超時時間 默認2000 -->
<property name="timeout" value="${redis.timeout}"/>
<!-- 連接池配置引用 -->
<property name="poolConfig" ref="poolConfig"/>
<!-- 是否使用連接池 -->
<property name="usePool" value="true"/>
<!-- 指定使用的數(shù)據(jù)庫 -->
<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) -> {
? ? ? ? ? ? // 打開管道
? ? ? ? ? ? redisConnection.openPipeline();
? ? ? ? ? ? // 給本次管道內(nèi)添加,一次性執(zhí)行的多條命令
? ? ? ? ? ? for (String redisValue : redisValues) {
? ? ? ? ? ? ? ? redisConnection.rPush(redisKey.getBytes(), redisValue.getBytes());
? ? ? ? ? ? }
? ? ? ? ? ? return null;
? ? ? ? });
? ? }redis客戶端:value是字符串

3、取值
此次取值,返回結(jié)果默認是按照 1、配置redisTemplate中配置的JdkSerializationRedisSerializer序列化方式,由于存和取的序列化方式不統(tǒng)一,會產(chǎn)生報錯情況。
public void testRedisListPop() {
String redisKey = "testGoodsKey";
// 使用管道從redis list結(jié)構(gòu)中批量獲取元素
List<Object> objects = redisTemplate.executePipelined((RedisConnection redisConnection) -> {
// 打開管道
redisConnection.openPipeline();
for (int i = 0; i < 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.<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)⒅性偌右粋€參數(shù):redisTemplate.getStringSerializer(),取值成功,解決問題??!
?? ?public void testRedisListPop() {
? ? ? ? String redisKey = "testGoodsKey";
? ? ? ? // 使用管道從redis list結(jié)構(gòu)中批量獲取元素
? ? ? ? List<Object> objects = redisTemplate.executePipelined((RedisConnection redisConnection) -> {
? ? ? ? ? ? // 打開管道
? ? ? ? ? ? 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ù)注意點:
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) -> {
? ? ? ? ? ? // 打開管道
? ? ? ? ? ? redisConnection.openPipeline();
? ? ? ? ? ? // 給本次管道內(nèi)添加,一次性執(zhí)行的多條命令
? ? ? ? ? ? for (String redisValue : redisValues) {
? ? ? ? ? ? ? ? redisConnection.rPush(redisKey.getBytes(), redisValue.getBytes());
? ? ? ? ? ? }
? ? ? ? ? ? return null;
? ? ? ? });
? ? }redis客戶端數(shù)據(jù)展示

c.不同點:
原生redisTemplate操作數(shù)據(jù)序列化方式是和redis配置統(tǒng)一的,redisTemplate回調(diào)函數(shù)操作數(shù)據(jù)序列化方式是自定義的。存值取值是需要注意。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- RedisTemplate默認序列化方式顯示中文亂碼的解決
- RedisTemplate序列化設(shè)置的流程和具體步驟
- redis redistemplate序列化對象配置方式
- 配置redis的序列化,注入RedisTemplate方式
- Spring?boot?RedisTemplate?序列化服務(wù)化配置方式
- Springboot下RedisTemplate的兩種序列化方式實例詳解
- Springboot?引入?Redis?并配置序列化并封裝RedisTemplate?
- 解決RedisTemplate的key默認序列化器的問題
- Spring的RedisTemplate的json反序列泛型丟失問題解決
相關(guān)文章
Redis之SDS數(shù)據(jù)結(jié)構(gòu)的使用
本文主要介紹了Redis之SDS數(shù)據(jù)結(jié)構(gòu)的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
深入理解Redis內(nèi)存回收和內(nèi)存淘汰機制
Redis使用多種過期策略和內(nèi)存淘汰機制來管理內(nèi)存,本文主要介紹了深入理解Redis內(nèi)存回收和內(nèi)存淘汰機制, 具有一定的參考價值,感興趣的可以了解一下2024-06-06

