使用spring-boot-starter-data-redis访问redis入门示例(默认使用Lettuce)

it2022-05-05  213

1、 引入依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>

需要注意: 官方默认使用的是Lettuce,不是Jedis。

可以看到spring-boot-starter-data-redis内部只引入了lettuce的依赖。 如果想要使用Jedis,在官方指南中有说明 [传送门]

2、redis基本配置

在application.properties文件中配置redis信息。

# ############################ Redis配置 ######################### # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=192.168.224.130 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password=password # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=20000 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=20000

3、使用RedisTemplate操作Redis

package com.tao.springboot.demo; import org.junit.Assert; 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.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = {SpringbootDemoApplication.class}) // 必需指定启动类 public class SpringbootDemoApplicationTests { @Autowired private RedisTemplate<String, String> redisTemplate; @Test public void contextLoads() { } @Test public void testRedis() { redisTemplate.opsForValue().set("name", "zhangsan"); Assert.assertEquals("zhangsan", redisTemplate.opsForValue().get("name")); } }

最新回复(0)