PASSWORD RESET

Your destination for complete Tech news

How do expire Redis keys?

594 0
< 1 min read

In Redis, you can use the “EXPIRE” command to set an expiration time for a key, after which the key will be automatically deleted. The command takes two arguments: the key, and the number of seconds after which the key should expire.

For example, to set an expiration time of 30 minutes (1800 seconds) for a key called “mykey”, you can use the following command:

EXPIRE mykey 1800

You can also use the “PEXPIRE” command to set an expiration time in milliseconds

PEXPIRE mykey 1800000

You can also use the “EXPIREAT” command to set an expiration time for a key as a UNIX timestamp.

EXPIREAT mykey 1623456789

You can also use redis-py library to handle expiration of keys in Redis.

import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.expire("mykey", 1800) # expire in 30 minutes

You can check if a key has an expiration time set by using the “TTL” command, which returns the remaining time to live of a key in seconds.

TTL mykey

You can also use the “PTTL” command to get the remaining time to live of a key in milliseconds

PTTL mykey

It’s important to notice that expiration time is only set for the key and not for its value, so if you know that a certain value will no longer be needed, you can delete the key manually using the “DEL” command.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.