时间:2022-03-09来源:www.pcxitongcheng.com作者:电脑系统城
对于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; } } |
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回调函数操作数据序列化方式是自定义的。存值取值是需要注意。
2023-11-01
React中immutable的使用2023-11-01
命令行清除Redis缓存的实现2023-11-01
Redis缓存空间优化实践详解引言大厂很多项目都是部署到多台服务器上,这些服务器在各个地区都存在,当我们访问服务时虽然执行的是同一个服务,但是可能是不同服务器运行的;在我学习项目时遇到这样一个登录情...
2023-11-01
1.多次修改一个redis的String过期键,如何保证他仍然能保留第一次设置时的删除时间 2.修改hash、set、Zset、list的值,会使过期时间重置吗?...
2023-11-01