一、Redis介绍
- Redis是一个开源的,键值(Key-Value)存储数据库。它支持数据结构有字符串,哈希,列表,集合,带有范围查询的排序集,位图,超文本和具有半径查询的地理空间索引。 NoSQL [ Not Only SQL],泛指非关系型的数据库。所以Redis是键值(Key-Value)存储NoSQL数据库。
二、应用步骤
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置数据源
# Redis服务器地址
spring.redis.host=192.168.1.20
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码
#spring.redis.password=
#Redis数据库索引(默认为0)
spring.redis.database=3
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.pool.max-active=16
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
3、操作类
@Component
public class RedisHelper {
@Autowired
private StringRedisTemplate redisTemplate;
public void setKey(String key,String value){
//2小时过期
redisTemplate.opsForValue().set(key,value,2, TimeUnit.HOURS);
}
public String getValue(String key){
return redisTemplate.opsForValue().get(key);
}
}
三、单元测试
@SpringBootTest
@Slf4j
class RedisHelperTest {
@Autowired
RedisHelper redisHelper;
@Test
void setKey() {
redisHelper.setKey("token", UUID.randomUUID().toString());
}
@Test
void getValue() {
log.info("token -> {}", redisHelper.getValue("token"));
}
}
单元测试输出结果
getValue key: token, value: 2f759257-57dd-421e-b28b-c788eab80244
四、相关资料
- 源码地址:my-spring-boot
- 对应分支:data-redis