RedisTemplate配置 序列和反序列化
對于redis操作,springboot進行了很好的封裝,那就是spring data redis。提供了一個高度封裝的RedisTemplate類來進行一系列redis操作,連接池自動管理;同時將事務封裝操作,交由容器進行處理。
針對數據的“序列化和反序列化”,提供了多種策略(RedisSerializer)
默認為使用JdkSerializationRedisSerializer,同時還有StringRedisSerializer,JacksonJsonRedisSerializer,OxmSerializer,GenericFastJsonRedisSerializer。
簡介一下
JdkSerializationRedisSerializer:POJO對象的存取場景,使用JDK本身序列化機制,將pojo類通過ObjectInputStream/ObjectOutputStream進行序列化操作,最終redis-server中將存儲字節序列。是目前默認的序列化策略。
StringRedisSerializer:Key或者value為字符串的場景,根據指定的charset對數據的字節序列編碼成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封裝。是最輕量級和高效的策略。
JacksonJsonRedisSerializer:jackson-json工具提供了javabean與json之間的轉換能力,可以將pojo實例序列化成json格式存儲在redis中,也可以將json格式的數據轉換成pojo實例。因為jackson工具在序列化和反序列化時,需要明確指定Class類型,因此此策略封裝起來稍微復雜。【需要jackson-mapper-asl工具支持】
GenericFastJsonRedisSerializer:另一種javabean與json之間的轉換,同時也需要指定Class類型。
OxmSerializer:提供了將javabean與xml之間的轉換能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存儲的數據將是xml工具。不過使用此策略,編程將會有些難度,而且效率最低;不建議使用。【需要spring-oxm模塊的支持】
實踐
1)依賴(版本繼承了SpringBoot版本)
1
2
3
4
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-redis</ artifactId > </ dependency > |
2)RedisConfig類
添加bean,指定key/value以及HashKey和HashValue的序列化和反序列化為FastJson的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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(); // 設置key和value的序列化規則 redisTemplate.setKeySerializer( new GenericToStringSerializer<>(Object. class )); redisTemplate.setValueSerializer(genericFastJsonRedisSerializer); // 設置hashKey和hashValue的序列化規則 redisTemplate.setHashKeySerializer( new GenericToStringSerializer<>(Object. class )); redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer); // 設置支持事物 redisTemplate.setEnableTransactionSupport( true ); redisTemplate.afterPropertiesSet(); return redisTemplate; } } |
RedisTemplate序列化問題
序列化與反序列化規則不一致,導致報錯問題
1、配置redisTemplate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
<!-- redis數據源 --> < bean id = "poolConfig" class = "redis.clients.jedis.JedisPoolConfig" > <!-- 最大空閑數 --> < property name = "maxIdle" value = "${redis.maxIdle}" /> <!-- 最大空連接數 --> < 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" /> <!-- 指定使用的數據庫 --> < 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的回調函數,是按照字符串序列化方式存redisValue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public void testRedisListPush() { String redisKey = "testGoodsKey" ; List<String> redisValues = Arrays.asList( "10002001" , "10002002" ); // 使用管道向redis list結構中批量插入元素 redisTemplate.executePipelined((RedisConnection redisConnection) -> { // 打開管道 redisConnection.openPipeline(); // 給本次管道內添加,一次性執行的多條命令 for (String redisValue : redisValues) { redisConnection.rPush(redisKey.getBytes(), redisValue.getBytes()); } return null ; }); } |
redis客戶端:value是字符串
3、取值
此次取值,返回結果默認是按照 1、配置redisTemplate中配置的JdkSerializationRedisSerializer序列化方式,由于存和取的序列化方式不統一,會產生報錯情況。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public void testRedisListPop() { String redisKey = "testGoodsKey" ; // 使用管道從redis list結構中批量獲取元素 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入參中再加一個參數:redisTemplate.getStringSerializer(),取值成功,解決問題!!
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public void testRedisListPop() { String redisKey = "testGoodsKey" ; // 使用管道從redis list結構中批量獲取元素 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); } |
總結
1、使用原生redisTemplate操作數據和redisTemplate回調函數操作數據注意點:
a.原生redisTemplate操作數據
代碼
1
2
3
4
5
|
public void testRedisListPush() { String redisKey = "testGoodsKey" ; List<String> redisValues = Arrays.asList( "10002001" , "10002002" ); redisValues.forEach(redisValue -> redisTemplate.opsForList().rightPush(redisKey, redisValue)); } |
redis客戶端數據展示
b.redisTemplate回調函數操作數據
代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public void testRedisListPush() { String redisKey = "testGoodsKey" ; List<String> redisValues = Arrays.asList( "10002001" , "10002002" ); // 使用管道向redis list結構中批量插入元素 redisTemplate.executePipelined((RedisConnection redisConnection) -> { // 打開管道 redisConnection.openPipeline(); // 給本次管道內添加,一次性執行的多條命令 for (String redisValue : redisValues) { redisConnection.rPush(redisKey.getBytes(), redisValue.getBytes()); } return null ; }); } |
redis客戶端數據展示
c.不同點:
原生redisTemplate操作數據序列化方式是和redis配置統一的,redisTemplate回調函數操作數據序列化方式是自定義的。存值取值是需要注意。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/chen15369337607/article/details/104058934