Dragonfly

Deleting a Redis Key After a Certain Time in Java (Detailed Guide w/ Code Examples)

Use Case(s)

  1. Session management in web applications: If you want to automatically log out users after a certain period of inactivity.
  2. Caching: To keep data available for a specific period, after which it should be re-fetched or calculated.

Code Examples

Let’s use Jedis, a popular Java client for Redis. You can add keys that expire by using the pexpire (with time in milliseconds) or expire (with time in seconds) commands.

Here's an example of setting a key with an expiration time:

import redis.clients.jedis.Jedis;

Jedis jedis = new Jedis('localhost');
jedis.set('key', 'value');
jedis.expire('key', 60); // The key will be deleted after 60 seconds

And here's another example using pexpire:

import redis.clients.jedis.Jedis;

Jedis jedis = new Jedis('localhost');
jedis.set('key', 'value');
jedis.pexpire('key', 60000); // The key will be deleted after 60000 milliseconds (60 seconds)

Best Practices

Common Mistakes

FAQs

Q: What happens if I try to access a key after its set expiration time?

A: If a key is accessed after its set expiration time, Redis would have already automatically deleted it. Therefore, it will appear as if the key does not exist.

Was this content helpful?

Similar Code Examples

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost