【Spring boot】RedisTemplate中String、Hash、List设置过期时间

文章目录

前言

时间类型:TimeUnit

java 复制代码
import java.util.concurrent.TimeUnit;

TimeUnit.SECONDS:秒
TimeUnit.MINUTES:分
TimeUnit.HOURS:时
TimeUnit.DAYS:日
TimeUnit.MILLISECONDS:毫秒
TimeUnit.MILLISECONDS:微秒
TimeUnit.NANOSECONDS:纳秒

Redis中String设置时间的方法

java 复制代码
redisTemplate.opsForValue().set("loginCode","254588",2, TimeUnit.SECONDS);//过期时间2秒
redisTemplate.opsForValue().set("loginCode","254588",2, TimeUnit.MINUTES);//过期时间2分钟
redisTemplate.opsForValue().set("loginCode","254588",2, TimeUnit.HOURS);//过期时间2小时
redisTemplate.opsForValue().set("loginCode","254588",2, TimeUnit.DAYS);//过期时间2天

Redis中Hash和List设置时间的方法

Java对于Redis的封装不是能满足所有的业务需求的,但是我们可以通过lua脚本来直接向Redis发送命令从而保证原子性;

下面这两句话,可以实现向Redis插入Hash数据,并且设置整个Hash的过期时间。

putIfAbsent 指的是如果传入key对应的value已经存在,就返回存在的value,不进行替换。如果不存在,就添加key和value,返回null。意思就是如果没有才插入。

java 复制代码
boolean a = redisTemplate.opsForHash().putIfAbsent(name, k, v);
boolean b = redisTemplate.expire(name, keepTime, TimeUnit.SECONDS);

Redis中Hash的put、putAll、putIfAbsent区别

put

向Redis添加单个key、hashKey、hashValue

putAll

添加整个hash

putIfAbsent

如果传入key对应的value已经存在,就返回存在的value,不进行替换。如果不存在,就添加key和value,返回null。

相关推荐
小王不爱笑1321 小时前
@PropertySource&@ImportResource&@Bean
spring boot
Wyy_9527*1 小时前
行为型设计模式——状态模式
java·spring boot·后端
编程彩机2 小时前
互联网大厂Java面试:从分布式事务到微服务架构场景应用
spring boot·分布式事务·微服务架构·java面试·电商场景
梅梅绵绵冰2 小时前
springboot初步2
java·spring boot·后端
VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue教务管理系统(源码+数据库+文档)
vue.js·spring boot·课程设计
小北方城市网3 小时前
Spring Cloud Gateway 自定义过滤器深度实战:业务埋点、参数校验与响应改写
运维·jvm·数据库·spring boot·后端·mysql
梅梅绵绵冰3 小时前
springboot初步1
java·前端·spring boot
jason.zeng@15022074 小时前
POM构造Spring boot多模块项目
java·spring boot·后端
indexsunny4 小时前
互联网大厂Java面试实录:Spring Boot微服务在电商场景中的应用与挑战
java·spring boot·redis·mysql·security·microservices·interview
猿与禅4 小时前
Spring Boot 3.x 集成 Caffeine 缓存框架官方指南
spring boot·后端·缓存·caffeine