目录
比较Jedis和Lettuce
Springboot整合时使用springboot-data-redis 。在spinrbgoot2.x以后,原来使用的jedis数据源被替换成了lettuce。
- jedis:采用直连,多个线程操作是不安全的,想要避免需要使用jedis pool。更像BIO模式
- lettuce:底层采用netty进行通信,实例可以在多个线程中共享,不存在不安全的情况,也可以减少线程数据量。更像NIO模式
基本整合
1.新建springboot项目,依赖如下
<dependencies>
<!-- 操作redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2.在properties文件中配置redis
#配置redis
spring.redis.host=192.168.62.130
spring.redis.port=6379
3.测试类中进行测试
@SpringBootTest
class Redis02SpringbootApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
// redisTemplate 操作不同的数据类型,api和我们的指令是一样的
// opsForValue 操作字符串 类似String
// opsForList 操作List 类似List
// opsForSet
// opsForHash
// opsForZSet
// opsForGeo
// opsForHyperLogLog
// 除了基本的操作,我们常用的方法都可以直接通过redisTemplate操作,比如事务,和基本的CRUD
redisTemplate.opsForValue().set("mykey","Dior香水");
System.out.println(redisTemplate.opsForValue().get("mykey"));
}
}
这里有个问题。你输入中文,控制台显示的是“Dior香水”,但你在redis客户端上查看key时,会发现它存的格式却是这样的。这说明在打印时redisTemplate工具类帮我们转码了,
RedisTemplate的使用
RedisTemplate是Springboot为我们封装好的redis操作方法。我们来看下RedisTemplate的源码,如果你自定义一个RedisTemplate,默认提供的就会失效。
@Bean
@ConditionalOnMissingBean(name = "redisTemplate") // 我们可以自己定义一个redisTemplate来替换这个默认的!
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
// 默认的 RedisTemplate 没有过多的设置,redis 对象都是需要序列化!
// 两个泛型都是 Object, Object 的类型,我们后使用需要强制转换 <String, Object>
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean // 由于 Stri