📜  nodejs redis setex - Javascript(1)

📅  最后修改于: 2023-12-03 14:44:44.172000             🧑  作者: Mango

Node.js Redis setex

Node.js Redis setex is a method in the Redis client that allows you to set a key-value pair with an expiration time in seconds. This means that after a set time, the key-value pair will be automatically deleted from Redis.

Installation

To use the setex method in Node.js with Redis, you will need to install the Redis module using npm. Run the following command in your terminal:

npm install redis
Example Usage

Here is an example of how you can use the setex method in Node.js to set a key-value pair with an expiration time of 300 seconds (5 minutes):

const redis = require('redis');

// create a Redis client
const client = redis.createClient();

// set the key-value pair with an expiration time of 300 seconds (5 minutes)
client.setex('key', 300, 'value', (err, response) => {
  if (err) throw err;
  console.log(response);
});

In the example above, we first create a Redis client using the redis module. We then use the setex method to set the key-value pair with the key 'key', the value 'value', and an expiration time of 300 seconds. Finally, we log the response from Redis.

Parameters

The setex method takes the following parameters:

  • key: the key to set the value for (string)
  • seconds: the expiration time for the key-value pair in seconds (number)
  • value: the value to set for the key (string)
  • callback: a callback function which is called with (err, response) where err is any error that occurred and response is the response from Redis (function)
Conclusion

Node.js Redis setex is a useful method when you need to set a key-value pair in Redis with an expiration time. It allows your application to automatically delete data from Redis after a specified time, helping to keep your Redis database clean and organized.