【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。

相关推荐
sevenlin8 分钟前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
salipopl11 分钟前
Spring Boot 集成 MyBatis 全面讲解
spring boot·后端·mybatis
Java水解29 分钟前
Spring Boot 数据仓库与ETL工具集成
spring boot·后端
beata37 分钟前
Spring Boot基础-3:Spring Boot 4.x 配置文件全攻略与多环境切换
spring boot·后端
jolimark42 分钟前
Spring Boot 集成 Kettle
java·spring boot·后端
无限进步_1 小时前
深入解析list:一个完整的C++双向链表实现
开发语言·c++·git·链表·github·list·visual studio
gaozhiyong08131 小时前
SpringBoot连接多数据源MySQL、SqlServer等(MyBatisPlus测试)
spring boot·mysql·sqlserver
zb200641202 小时前
Spring Boot 实战篇(四):实现用户登录与注册功能
java·spring boot·后端
分享牛2 小时前
Operaton入门到精通22-Operaton 2.0 升级指南:Spring Boot 4 核心变更详解
java·spring boot·后端
jinanmichael2 小时前
SpringBoot 如何调用 WebService 接口
java·spring boot·后端