说明:在SpringBoot2.x之后,原来使用的jedis被替换成了lettuce
jedis:采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用jedis pool连接池!更像BIO模式
lettuce:采用netty,实例可以在多个线程中进行共享,不存在线程不安全的情况!可以减少线程数据了,更像NIO模式
源码分析
@Bean @ConditionalOnMissingBean(name = "redisTemplate") //我们可以自己定义一个redisTemplate来替换这个默认的! @ConditionalOnSingleCandidate(RedisConnectionFactory.class) public RedisTemplate第一步:创建项目,添加依赖
第二步:application.yml4.0.0 org.springframework.boot spring-boot-starter-parent 2.6.4 com.example redis-02-springboot 0.0.1-SNAPSHOT redis-02-springboot redis-02-springboot 1.8 org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-devtools runtime true org.springframework.boot spring-boot-configuration-processor true org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok
#SpringBoot 所有的配置类,都有一个自动配置类 RedisAutoConfiguration #自动配置类都会绑定一个properties配置文件 RedisProperties #配置redis spring.redis.host=192.168.222.200 spring.redis.port=6379第三步:测试代码
package com.example;
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;
@SpringBootTest
class Redis02SpringbootApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
//redisTemplate 操作不同的数据类型,api和redis指令是一样的
//opsForValue 操作字符串
//opsForList 操作list
//......
//除了基本的操作,我们常用的方法都可以直接通过redisTemplate操作,比如事务和基本的curd
//获取redis的连接对象
//RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
//connection.flushAll();
//connection.flushDb();
redisTemplate.opsForValue().set("mykey","张三");
System.out.println(redisTemplate.opsForValue().get("mykey"));
}
}



