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

相关推荐
q***54752 分钟前
springboot之集成Elasticsearch
spring boot·后端·elasticsearch
q***25113 分钟前
Spring Boot 中使用 @Transactional 注解配置事务管理
数据库·spring boot·sql
q***318921 分钟前
Spring Boot 实战篇(四):实现用户登录与注册功能
java·spring boot·后端
哥哥还在IT中33 分钟前
缓存架构设计模式:Cache-Aside, Read-Through/Write-Through详解
spring boot·spring·缓存
低调波33 分钟前
springboot实现批量下载
windows·spring boot·后端
j***12157 小时前
Spring Boot中Tomcat配置
spring boot·tomcat·firefox
z***67777 小时前
SpringBoot(整合MyBatis + MyBatis-Plus + MyBatisX插件使用)
spring boot·tomcat·mybatis
Filotimo_9 小时前
Spring Boot 整合 JdbcTemplate(持久层)
java·spring boot·后端
没有bug.的程序员11 小时前
JVM 整体架构:一套虚拟机的心脏与血管
java·jvm·spring boot·spring cloud·架构
i020812 小时前
SpringBoot 项目配置
java·spring boot·后端