If you would have worked with the Redis command, you must be familiar with the below SET options that you can use to set expiration or TTL for a key.
| Option | : | What it does? |
|---|---|---|
| EX | : | Sets expiration time in seconds. |
| EXAT | : | Sets the Unix time at which the key will expire in seconds. |
| PX | : | Sets expiration time in milliseconds. |
| PXAT | : | Sets the Unix time at which the key will expire in milliseconds. |
| KEEPTTL | : | Retain the TTL value associated with the key. |
Let us see examples of each of the with Spring Boot.
EX: Setting expiration time in seconds
@Autowired
private RedisTemplate redisTemplate;
private long expirationTimeInSeconds = 1;
public void setKeyWithEx() throws InterruptedException {
redisTemplate.opsForValue().set("city", "New York", Duration.ofSeconds(expirationTimeInSeconds));
Thread.sleep(3000);
System.out.println(redisTemplate.opsForValue().get("message"));
}
As we have set the EX duration of 1 second and have added a thread sleep of 3 seconds we get a null response as the key got deleted before retrieval.
EXAT: Setting the Unix time at which the key will expire in seconds.
public void setKeyWithEXAT() {
Instant instant = Instant.ofEpochSecond(expirationTimeInSeconds);
redisTemplate.opsForValue().set("city", "New York", Duration.between(Instant.now(),instant));
}
PX: Setting expiration time in milliseconds
@Autowired
private RedisTemplate redisTemplate;
private long expirationTimeInMilliSeconds = 1;
public void setKeyWithPX() {
redisTemplate.opsForValue().set("city", "New York", Duration.ofMillis(expirationTimeInMilliSeconds));
}
PXAT: Setting the Unix time at which the key will expire in milliseconds.
public void setKeyWithPXAT() {
Instant instant = Instant.ofEpochMilli(expirationTimeInMilliSeconds);
redisTemplate.opsForValue().set("city", "New York", Duration.between(Instant.now(),instant));
}
PXAT: we want to preserve the existing time-to-live (TTL) value of a key.
@Autowired
private StringRedisTemplate redisTemplate;
public void setKeepTtlValue() {
redisTemplate.execute(connection -> {
byte[] keyBytes = redisTemplate.getKeySerializer().serialize("city");
byte[] valueBytes = redisTemplate.getValueSerializer().serialize("Chicago"); //setting a new value
Boolean result = connection.set(keyBytes, valueBytes, Expiration.KEEP_TTL, RedisStringCommands.SetOption.UPSERT);
System.out.println(result);
});
}
You should get a result as a boolean true.
Related Tutorials
- String Boot + Redis - SET and GET String Commands Examples
- Spring Boot + Redis Cloud Configuration and Setup
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!