设置redis缓存的key有效期一天,每天凌晨失效

您所在的位置:网站首页 java设置时间 设置redis缓存的key有效期一天,每天凌晨失效

设置redis缓存的key有效期一天,每天凌晨失效

2024-07-14 09:11| 来源: 网络整理| 查看: 265

实际项目开发过程中我们需要设置某个redis的key只保留一天,如刷新时间日期的key

redisTemplate.opsForValue().set(CHARGEBI_YEAR_WEEKS, "2022-04-25",seconds, TimeUnit.SECONDS);

所以我们在设置的key的时候就需要计算当前时间离凌晨的秒数

方案一: 使用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; }



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3