Springboot 整合redis
一、redis是什么?
Redis(Remote Dictionary Server ),即远程字典服务,是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
二、使用步骤
1.引入maven依赖
代码如下(示例规范化):
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.redis配置
在yml配置文件里写入以下配置信息。
spring:
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
# Redis服务器连接端口
port: 6379
# Redis服务器连接密码(默认为空)
# password:
# 连接超时时间
timeout: 10s
lettuce:
pool:
# 连接池最大连接数
max-active: 200
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
# 连接池中的最大空闲连接
max-idle: 10
# 连接池中的最小空闲连接
min-idle: 0
3.自动装配
在service层通过@Autowired注解注入容器
@Autowired
StringRedisTemplate stringRedisTemplate;
4.内置方法
stringRedisTemplate.opsForValue().set(key,value,timeout,unit); //存入key,value
stringRedisTemplate.delete(key); //删除key
总结
注意:stringRedisTemplate的[key,value]都是String类型的。
unit有2个注意的参数:(特别注意)
1.TimeUnit.MILLISECONDS --->表示毫秒
2.TimeUnit.MICROSECONDS --->表示微秒
3.TimeUnit.SECONDS --->表示秒
4.TimeUnit.NANOSECONDS --->表示毫微秒
``
注意
有时候拿不到redis的key或者没有存进去,可能是设置了TimeUnit.MICROSECONDS。因为时间太小了,时间过期太快,所有才获取不到。