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版本)
<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();
// 设置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
<!-- 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
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序列化方式,由于存和取的序列化方式不统一,会产生报错情况。
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(),取值成功,解决问题!!
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操作数据
代码
public void testredislistpush() {
string rediskey = "testgoodskey";
list<string> redisvalues = arrays.aslist("10002001", "10002002");
redisvalues.foreach(redisvalue -> redistemplate.opsforlist().rightpush(rediskey, redisvalue));
}
redis客户端数据展示
b.redistemplate回调函数操作数据
代码
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回调函数操作数据序列化方式是自定义的。存值取值是需要注意。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。