YuJia
YuJia

Reputation: 91

How to make redis expire at an exact time in java?

example: I want make redis string "aKey":"aValue" expired at a future time(2018.08.17 00:00, now is 2018.08.16 12:00), this is my solution:

long expireTime = Date.from(LocalDateTime.now().with(LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant()).getTime() - Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()).getTime();
redisTemplate.opsForValue().set("aKey","aValue",expireTime, TimeUnit.SECONDS);

I want a perfect solution.

Upvotes: 2

Views: 3593

Answers (1)

YuJia
YuJia

Reputation: 91

Thanks for your help, I got it. Redis has an "EXPIREAT" command, which can be used like this in Java:

redisTemplate.opsForValue().set("aKey","aValue");
redisTemplate.expireAt("aKey",Date.from(LocalDateTime.now().with(LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant()));

Upvotes: 7

Related Questions