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
Facing issues? Have Questions? Post them here! I am happy to answer!
Author Info:
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
More Posts related to Java,
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
More Posts:
- Fix Windows Update Error Code: 0x80070643 - Windows
- How to Only Show File name instead of Complete File Path on Notepad++ - NotepadPlusPlus
- How to Uninstall Android Studio on Mac - Android-Studio
- Display ls command file sizes in KB (kilobytes) MB (megabytes) or GB (gigabytes) [Linux/macOS] - MacOS
- Best way to Store Date of Birth in Java 8 and Above - Java
- npm WARN saveError ENOENT: no such file or directory, open /mnt/c/package.json - JavaScript
- iOS 14 Airpods Connected message everytime when the iPhone is unlocked - Apple
- Fix: java.util.regex.PatternSyntaxException - Java