Spring Boot整合Spring Data Redis-存取Java对象
如何通过Spring Data Redis,来将我们一个实体对象,做一个存储的操作,Spring Data Redis操作实体对象,我们回到代码当中,我们首先去创建一个实体,比如我这个实体叫Users,我把它放到POJO的包下,记下来我想通过RedisTemlate这个对象,将我们的user对象,直接放到Redis里去存储,它会怎么去操作,我们写一个测试方法@Test
public void testSetUesrs(){Users users = new Users();users.setAge(20);users.setName("张三丰");users.setId(1);//重新设置序列化器this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());this.redisTemplate.opsForValue().set("users", users);
}那么我们先回顾一下,我们自己用Redis的时候,没有用Spring Data Redis的时候,我们想将一个对象存到Redis缓存当中,怎么去做呢,我们是不是要将这个对象做序列化处理,就是我们通过看一个JSON的工具类,把它转换成一个JSON字符串,把JSON串放到Redis当中,其实我们RedisTemplate,他提供的对于User对象,或者实体对象的一个存取,他也是使用了这样的一个原则,他不是我们想象的,给我一个user,直接在redis里做存储了,因为这不符合redis的存储规则,只不过相比较我们自己使用redis的时候,去做一个JSON对象转换,相比这样一个过程来讲,我们使用RedisTemplate会相对比较容易,为什么呢,我们只要给他一个序列化器就可以了,我们说过序列化器的问题,我们现在用的序列化器是谁呢,用的是字符串序列化器,key和value都是用的字符串序列化器,StringRedisSerializer,你存的所有内容都会作为字符串来存储,那么我们就用这个序列化器,能不能将user对象存入到Redis当中,不能将一个user对象转成一个String,也就是我们现在用的序列化器,这个字符串的序列化器,这个序列化器的特点呢,你所有的东西给你转成字符串,但是我现在是一个user对象,他怎么把一个user对象转成一个字符串呢,没法去变,如果我们要去做一个对象的存储,我们肯定得换一个序列化器,这个过程呢,就相当于以往自己在操作Redis的时候,将对象转成JSON的这样一个处理,只不过现在不用那么麻烦了,我们怎么去做呢,在调用set方法之前呢,我们是对value的,key不用管this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());因为key我们只要用字符串就可以了,value并不是一个串,而是一个实体对象,换哪个序列化器呢,打开Spring-data-redis的jar包,这里有一个Serializer,我们之前用的是StringRedisSerializer,我们看到有一个JdkSerializationRedisSerializer,有这样的一个序列化器,这个序列化器是什么意思呢,我会把你的value,只要value设置序列化器了,那我会给你的value采用JDK的序列化方式,将他变成一个字节,字节以字符的方式存在redis当中,那么在这里我们知道,user对象肯定可以被JDK的序列化,所以这里我们可以换成JdkSerializationRedisSerializer,很简单,调set方法之前就可以,创建这个序列化,序列化器的对象,这样他再去调用set存储的时候,以字符的方式存在redis当中,我把序列化器设置好以后,不能序列化,因为你当前的实体类,没有实现默认的序列化,什么意思呢,我们当前的实体类,是没有实现序列化接口的,我们JDK的序列化不就是要求必须要实现Serializable接口的,这也是同样的道理,需要让他实现Serializable这个接口,然后回过来,我们再去测试,我们看执行是成功的,没有出什么错误,重新reload,打开db0,我们看多了一个key叫users,就是我们在这里存的这个key,那么他所对应的value是什么呢,里面是不是乱码,那么其实这个乱码是正确的,因为我们这个对象被序列化以后,它是把对象变成了字节,然后把字节以字符的形式存在redis当中,所以把字节以字符转换后的就是乱码,这是没问题的,那么我们现在通过这个工具看到的乱码,如果存的成不成功呢,怎么是乱码,那我们接下来在做一个测试,我们去redis当中,把我们序列化的对象,取出来,如果能够取出来,我们是成功的,如何去取这个user对象/*** 取Users对象*/
@Test
public void testGetUsers(){//重新设置序列化器this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
//this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Users>(Users.class));Users users = (Users)this.redisTemplate.opsForValue().get("users");System.out.println(users);
}我们再来写一个测试方法,那么怎么去取呢,取得时候也有东西,我们不能直接调用opsForValue().get方法,你现在直接调,相当于把这里存的,你直接就做输出了,那肯定是不允许的,我们是不是要的是序列化后的内容再反序列化回来的结果,所以我们这里还要对他做一个反序列化的一个处理,我们才能拿到正确的user对象,所以怎么办呢,还是我们在去取之前,再把JdkSerializationRedisSerializer序列化器交给这个方法,然后去取才能取出来,否则是无法取出来的,应该会报一个异常,那我们接下来就可以取了,我们看是执行成功的,控制台也打印出来了,这就是通过Spring Data Redis提供的一个JdkSerializationRedisSerializer序列化器,对我们实体类,或者叫实体bean对象,做一个序列化存储的方式,其实他的原理和 我们自己使用JSON的方式是一样的,只不过我们不需要写JSON的工具类了,直接用他的序列化器就好了,那么相比我们的JSON还有一个好处就是,如果我们用JSON存储,其实在我们的Redis当中,我们是可以看到里面的信息的,但是如果使用JDK的来做呢,那么存储的就是转换以后的字节,直接看里面的内容会是一个乱码,这里还有一个点就是,我们在取这个对象的时候,一定要切记,这里一定要重新设置序列化器,除此之外你往里放的时候,也得重新设置序列化器,而且还得保证是同一个序列化器,否则还是无法序列化和反序列化处理的,以上就是通过Spring Data Redis,来做一个JAVABEAN对象,或者实体类对象的一个存储,我们把笔记整理一下,首先创建实体类,然后测试代码
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.learn</groupId><artifactId>spring-boot-redis</artifactId><version>0.0.1-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.12.RELEASE</version></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><!-- springBoot的启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Data Redis的启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- Test的启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency>
</dependencies>
</project>
spring.redis.pool.max-idle=10
spring.redis.pool.min-idle=5
spring.redis.pool.max-total=20
#
#aaa.bbb.max-idle=10
#aaa.bbb.min-idle=5
#aaa.bbb.max-total=20spring.redis.hostName=10.40.8.152
spring.redis.port=6379
spring.redis.password=1234
package com.learn.config;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;import redis.clients.jedis.JedisPoolConfig;/*** 完成对Redis的整合的一些配置***/
@Configuration
public class RedisConfig {/*** 1.创建JedisPoolConfig对象。在该对象中完成一些链接池配置* @ConfigurationProperties:会将前缀相同的内容创建一个实体。*/@Bean@ConfigurationProperties(prefix="spring.redis.pool")
// @ConfigurationProperties(prefix="aaa.bbb")public JedisPoolConfig jedisPoolConfig(){JedisPoolConfig config = new JedisPoolConfig();/*//最大空闲数config.setMaxIdle(10);//最小空闲数config.setMinIdle(5);//最大链接数config.setMaxTotal(20);*/System.out.println("默认值:"+config.getMaxIdle());System.out.println("默认值:"+config.getMinIdle());System.out.println("默认值:"+config.getMaxTotal());return config;}/*** 2.创建JedisConnectionFactory:配置redis链接信息*/@Bean@ConfigurationProperties(prefix="spring.redis")public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config){System.out.println("配置完毕:"+config.getMaxIdle());System.out.println("配置完毕:"+config.getMinIdle());System.out.println("配置完毕:"+config.getMaxTotal());JedisConnectionFactory factory = new JedisConnectionFactory();//关联链接池的配置对象factory.setPoolConfig(config);//配置链接Redis的信息//主机地址/*factory.setHostName("10.40.8.152");//端口factory.setPort(6379);*/return factory;}/*** 3.创建RedisTemplate:用于执行Redis操作的方法*/@Beanpublic RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory factory){RedisTemplate<String, Object> template = new RedisTemplate<>();//关联template.setConnectionFactory(factory);//为key设置序列化器template.setKeySerializer(new StringRedisSerializer());//为value设置序列化器template.setValueSerializer(new StringRedisSerializer());return template;}
}
package com.learn.pojo;import java.io.Serializable;public class Users implements Serializable {
// public class Users {private Integer id;private String name;private Integer age;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Users [id=" + id + ", name=" + name + ", age=" + age + "]";}}
package com.learn;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class RedisApp {public static void main(String[] args) {SpringApplication.run(RedisApp.class, args);}
}
package com.learn.test;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.learn.RedisApp;
import com.learn.pojo.Users;/*** Spring Data Redis测试*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=RedisApp.class)
public class RedisJdkSerializationTest {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;/*** 添加Users对象*/@Testpublic void testSetUesrs(){Users users = new Users();users.setAge(20);users.setName("张三丰");users.setId(1);//重新设置序列化器this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
// this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Users>(Users.class));this.redisTemplate.opsForValue().set("users", users);}/*** 取Users对象*/@Testpublic void testGetUsers(){//重新设置序列化器this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
// this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Users>(Users.class));Users users = (Users)this.redisTemplate.opsForValue().get("users");System.out.println(users);}}
Spring Boot整合Spring Data Redis-存取Java对象相关推荐
- springboot整合hibernate_峰哥说技术系列-17 .Spring Boot 整合 Spring Data JPA
今日份主题 Spring Boot 整合 Spring Data JPA JPA(Java Persistence API)是用于对象持久化的 API,是Java EE 5.0 平台标准的 ORM 规 ...
- 二、何为Spring Boot整合Spring Cloud?
题语:学习方法之多思考:正向.逆向.跳跃 作者:A哥(YourBatman) wx号:fsx641385712(备注"Java群"字样) 公众号:BAT的乌托邦(ID:BAT-ut ...
- Spring boot 整合Spring Security Jwt
记录学习Spring boot 整合Spring Security Jwt 学习参考 – 慢慢的干货 https://shimo.im/docs/OnZDwoxFFL8bnP1c/read 首先创建S ...
- spring boot整合spring security笔记
最近自己做了一个小项目,正在进行springboot和spring Security的整合,有一丢丢的感悟,在这里分享一下: 首先,spring boot整合spring security最好是使用T ...
- 认证与授权流程与spring boot整合 spring security(1)
一 spring security 1.1 spring security的作用 Spring Security所解决的问题就是安全访问控制,而安全访问控制功能其实就是对所有进入系统的请求进行拦截 ...
- spring boot 整合 spring cache 简单使用
spring boot 整合 spring cache 简单使用 spring cache简介 使用spring cache spring cache简介 Spring 3.1起,提供了基于注解的对C ...
- Spring Boot 整合——Spring batch重试和回滚
关于版本 依赖 版本 springboot 2.4.0 spring batch 2.4.0 代码地址 因为每个例子涉及代码较多,且包含测试用例,如果都贴到文章中内容过多,所以只贴出了部分代码.全部的 ...
- Spring Boot 整合——Spring Boot整合kafka整合
Spring Boot 整合之前的内容 项目名称 描述 地址 base-data-mybatis 整合mybatis-plus(实际上官方教程已经很多,只做了自定义插件) 未完成 base-jpa J ...
- Spring Boot整合Spring Data Redis-存取JSON格式Java对象
如何通过Spring Data Redis,以JSON格式来存储我们的实体对象,其实上节课我们讲了基于JDK的序列化器,来帮助我们做一个序列化,做一个对象的存储,那么这种方式需要注意一点的是,如果我们 ...
最新文章
- 中科大“九章”历史性突破,但实现真正的量子霸权还有多远?
- 滚动html颜色,利用CSS设置网页滚动条颜色
- java.sql.SQLException: ORA-01691: Lob 段 SONARQUBE2.SYS_LOB0000119128C00008$$ 无法通过 128 (在表空间 USERS 中
- 超详细前端开发案例:品优购商场项目(一)
- go 链路追踪_使用opentracing,jaeger实现golang链路追踪
- LINUX上用Robot截屏得到全黑之分析
- liteon460w服务器电源管理系统,PS-5251-06 LITEON光宝工业电源
- 破防了,原来这才是机房运维的正确方法
- 如何在html中插入表情包,一款支持插入表情的编辑器实现代码(简单思路挺重要)...
- 小梅哥Xilinx FPGA学习笔记6——参数化设计及模块重用设计流水灯(跑马灯)
- java网络爬虫如何控制爬取的深度_Java 动手写爬虫: 二、 深度爬取
- 都市青年图鉴:那些喊着奋斗的人,后来怎样了
- 搬上小板凳,听嵌入式大牛讲解硬核单片机编程思想!
- 二次规划及qpoases简要介绍
- 蓝牙技术|了解蓝牙LE Audio的Auracast广播音频
- python 进程详解
- Android自动股票,腾讯股票自选股 Android 版上线 - YangJunwei
- Java ASCII编码表和运算符
- 插图设计正流行,10大理由告诉你如何靠它增强用户体验
- oracle数据库27043,在线考试系统(论文).doc