这篇文章主要介绍“SpringBoot集成Redis操作API的方法”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“SpringBoot集成Redis操作API的方法”文章能帮助大家解决问题。
SpringDataRedis调用Redis底层解读
Jedis:采用直接连接,多线程操作不安全,如果想要避免不安全,使用Jedis pool连接池;BIO
lettuce:底层采用Netty,实例可以在多个线程之间共享,不存在线程不安全的情况,可以减少线程数量;NIO
SpringBoot整合Redis(源码分析)
SpringBoot所有的配置类,都有一个自动配置类
自动配置类都会绑定一个properties文件
在源码中找到Spring.factories

在里面搜索redis,找到AutoConfiguration

按ctrl+点击进入类

找到redisproperties.class

ctrl+点击进入

里面就是全部的redis相关配置了,先简单看一下,其他的后面再说

默认注入的Bean

但是默认的redisTemplate是存在一些问题的,他的key是Object类型的,但是我们期望的一般key都是String类型的这就需要强制类型转换了,所以上面提出了,可以自己定义RedisTemplate
在配置配置文件时,如果需要配置连接池,就采用lettuce的,不要直接配置Redis的,配置了也不生效
查看注入时的RedisConnectionFactory

他是存在两个子类的,分别是JedisConnectionFactory和LettuceConnectionFactory

为什么说直接JedisConnectionFactory不生效呢?是因为类中的很多依赖类都是不存在的

全都是爆红线的,而lettuceConnectionFactory中的依赖就是全部存在的

所以配置时,采用lettuce的

不要直接配置jedis的

SpringBoot整合Redis(配置)
yml
spring:
redis:
host: localhost
port: 6379
Maven
在项目创建的时候选择,如果没有选择就添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
编写测试
redisTemplate.unwatch();
redisTemplate.watch("key");
redisTemplate.multi();
redisTemplate.discard();
redisTemplate.exec();
关于数据库的操作需要获取链接后使用连接对象操作
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();connection.flushAll();connection.flushDb();connection.close();
测试代码及其执行结果
package co.flower.redis02springboot;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTestclass Redis02SpringbootApplicationTests {/** * 我居然直接就指定了泛型 RedisTemplate<String,Object>结果就直接报错了,删除泛型后成功 */@Autowiredprivate RedisTemplate redisTemplate;
@Testvoid contextLoads() {// 英文测试redisTemplate.opsForValue().set("name","xiaojiejie");
System.out.println(redisTemplate.opsForValue().get("name"));// 中文测试redisTemplate.opsForValue().set("name","小姐姐");
System.out.println(redisTemplate.opsForValue().get("name"));
}
}
执行结果,SpringBoot的启动加载和结束销毁没有粘贴/***SpringBootStart****/xiaojiejie
小姐姐/***SpringBootStop*****/
关于“SpringBoot集成Redis操作API的方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注天达云行业资讯频道,小编每天都会为大家更新不同的知识点。