You can add an expiry (time-to-live) to a key in Redis using the EXPIRE
or EXPIREAT
command. Here are the steps to add an expiry to a key in Redis:
Connect to your Redis server using the
redis-cli
command-line interface.Use the
SET
command to set the value of the key you want to expire. For example:SET mykey "Hello Redis"
Use the
EXPIRE
command to set the expiry time for the key in seconds. For example, to set the keymykey
to expire after 60 seconds, you can run:EXPIRE mykey 60
This command sets the key
mykey
to expire after 60 seconds. Once the expiry time is reached, the key will automatically be deleted from the Redis database.Alternatively, you can use the
EXPIREAT
command to set the expiry time for the key as an absolute Unix timestamp (in seconds since January 1, 1970). For example, to set the keymykey
to expire at midnight on January 1, 2024, you can run:EXPIREAT mykey 1704067200
This command sets the key
mykey
to expire at the Unix timestamp1704067200
.
Note that you can also use the SETEX
command to set a key with an expiry time in a single command. The SETEX
command sets the value of a key and its expiry time in a single atomic operation. For example, to set the key mykey
to expire after 60 seconds, you can run:
SETEX mykey 60 "Hello Redis"
This sets the value of the key mykey
to "Hello Redis"
and its expiry time to 60 seconds in a single command.
Comments
Post a Comment