spring data redis 使得开发者能够更容易地与 redis 数据库进行交互,并且支持不同的 redis 客户端实现,如 jedis 和 lettuce。
spring data redis 会自动选择一个客户端,通常情况下,spring boot 默认使用 lettuce 作为 redis 客户端。你也可以选择使用 jedis。
spring data redis 的使用步骤
(1)引入spring-boot-starter-data-redis依赖
<dependency>
<!--redia依赖-->
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>
<!--common-pool-->
<dependency>
<groupid>org.apache.commons</groupid>
<artifactid>commons-pool2</artifactid>
</dependency>(2)在application.yml配置redis信息
spring:
data:
redis:
host: 192.168.30.130
port: 6379
password: xxxxxx
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: 100ms(3)注入redistemplate
springdataredis 是 spring data redis 中最重要的工具类,其中封装了各种对redis的操作,并且将不同数据类型的操作api封装到了不同的类型中。
springdataredis 可以接受任何类型的java对象,并通过 redisserializer 将它们转成 redis 可以处理的字节(byte[])格式。
这是因为 redis 本身只能够存储字节数据,而不能直接存储 java 对象。因此,spring data redis 提供了自动序列化和反序列化机制来支持 java 对象的存储和读取。
@springboottest
class redisdemoapplicationtests {
@autowired
private redistemplate redistemplate;
@test
void teststring() {
//写入一条string数据
redistemplate.opsforvalue().set("name","虎哥");
//获取string数据
object name = redistemplate.opsforvalue().get("name");
system.out.println("name = " + name);
}
}redistemplate 默认使用 jdkserializationredisserializer 来序列化和反序列化对象,但它具有不可读性,jdk 序列化的字节流是二进制的,不易于人工读取或调试。如果你需要查看 redis 中存储的数据,jdk 序列化的对象将无法直接转换回人类可读的格式,这使得调试和监控变得困难。
可以自定义redistemplate的序列化方式,常见做法是key使用string序列化(stringredisserializer),value使用json序列化(genericjackson2jsonredisserializer)。这种方法可以自动帮我们处理json的序列化和反序列化,但是会占用额外空间。
所以为了节省空间,我们并不会使用json序列化器来处理value,而是统一使用string序列化器(stringredistemplate),要求只能存储string类型的key和value。当需要存储java对象时,手动把对象序列化为json,读取redis时手动把读取到的json反序列化为对象。
@springboottest
class redisstringtests {
@autowired
private stringredistemplate stringredistemplate;
@test
void teststring() {
//写入一条string数据
stringredistemplate.opsforvalue().set("name","虎哥");
//获取string数据
object name = stringredistemplate.opsforvalue().get("name");
system.out.println("name = " + name);
}
private static final objectmapper mapper = new objectmapper();
@test
void testsaveuser() throws jsonprocessingexception {
//创建对象
user user = new user("虎哥", 21);
//手动序列化
string json = mapper.writevalueasstring(user);
//写入数据
stringredistemplate.opsforvalue().set("user:200",json);
//获取数据
string jsonuser = stringredistemplate.opsforvalue().get("user:200");
//手动反序列化
user user1 = mapper.readvalue(jsonuser, user.class);
system.out.println("user1 = " + user1);
}
@test
void testhash() {
stringredistemplate.opsforhash().put("user:400","name","虎哥");
stringredistemplate.opsforhash().put("user:400","age","21");
map<object, object> entries = stringredistemplate.opsforhash().entries("user:400");
system.out.println("entries = " + entries);
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论