redis如何设置当天有效链接

前言
业务:设置一个redis缓存,每天的24点过期,需要设置redis的过期时间,直接使用24小时是不行的,因为我们不能保证每次都是0点0分0秒开始,所以我们需要算出当前时间到明天0点0分0秒的差值

方案一: 使用Calendar(Java 8之前)
getInstance()是Calendar提供的一个类方法,它的作用是获得一个Calendar类型的通用对象,getInstance()将返回一个Calendar的对象。
使用Calendar.getInstance()不仅能获取当前的时间,还能指定需要获取的时间点。

public static Integer getRemainSecondsOneDay(Date currentDate) {
Calendar midnight=Calendar.getInstance();
midnight.setTime(currentDate);
midnight.add(midnight.DAY_OF_MONTH,1);//将日加1
midnight.set(midnight.HOUR_OF_DAY,0);//控制时
midnight.set(midnight.MINUTE,0);//控制分
midnight.set(midnight.SECOND,0);//控制秒
midnight.set(midnight.MILLISECOND,0);//毫秒
//通过以上操作就得到了一个currentDate明天的0时0分0秒的Calendar对象,然后相减即可得到到明天0时0点0分0秒的时间差
Integer seconds=(int)((midnight.getTime().getTime()-currentDate.getTime())/1000);
return seconds;
}

方案二:Java8之后,我们可以使用localDateTime

Java8推出了线程安全、简易、高可靠的时间包,LocalDateTime其中之一

 

public static Integer getRemainSecondsOneDay(Date currentDate) {
//使用plusDays加传入的时间加1天,将时分秒设置成0
LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),
ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0)
.withSecond(0).withNano(0);
LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(),
ZoneId.systemDefault());
//使用ChronoUnit.SECONDS.between方法,传入两个LocalDateTime对象即可得到相差的秒数
long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
return (int) seconds;
}

获取到当前时间到24点0分0秒的相差秒数之后,我们就可以设置redis的过期时间了
 

//储存value并设置有效时间,seconds即为上面方法返回的秒数
redisTemplate.opsForValue().set(redisKey,redisValue,seconds,TimeUnit.SECONDS)

原文链接:https://www.waimaiguai.com/technology/article/3919848
 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值