nodejs redis setex
The setex
function in the Node.js Redis library is used to set a key-value pair in Redis with an expiration time. Here are the steps involved in using the setex
function:
Import the Redis module: In your Node.js application, you need to import the Redis module using the
require
keyword. This allows you to access the Redis library and its functions.Create a Redis client: After importing the Redis module, you need to create a Redis client using the
createClient
function. This function establishes a connection to the Redis server and returns a client object that you can use to interact with the Redis database.Set the key-value pair with an expiration time: To use the
setex
function, you need to call it on the Redis client object. Thesetex
function takes three parameters: the key, the expiration time in seconds, and the value. It sets the key-value pair in the Redis database and automatically sets an expiration time for the key.Handle the callback function: The
setex
function is asynchronous, meaning it doesn't block other operations while waiting for a response from the Redis server. Instead, it uses a callback function to handle the result of the operation. The callback function takes two parameters: an error object (if any) and the result of the operation.Close the Redis client: After finishing your Redis operations, it's good practice to close the Redis client connection to free up system resources. You can do this by calling the
quit
function on the Redis client object.
By following these steps, you can successfully use the setex
function in Node.js to set a key-value pair in Redis with an expiration time.