Redis Auto-Update Expiration Guide
Redis offers the feature of automatically refreshing expiration times, which can be achieved using the EXPIRE and TTL commands.
- Set the value of a key using the SET command and set an expiration time using the EXPIRE command, for example:
- Set the key with a specified value and set an expiration time for the key in seconds.
- When it is necessary to refresh the expiration time, one can use the TTL command to retrieve the remaining expiration time of a key, and then use the EXPIRE command to extend it, for example:
- Set a time-to-live (TTL) for a key
Set an expiration time for a key in seconds - Note: The TTL command returns -1 if the key exists indefinitely, and -2 if the key does not exist or has expired.
- You can use Redis transactions to ensure atomicity, meaning that no other operations will interfere between getting the remaining expiration time and setting a new expiration time.
Here is an example code using Redis for automatically refreshing expiration time (using Node.js and the ioredis library):
const Redis = require('ioredis');
const redis = new Redis();
const key = 'mykey';
const seconds = 60; // 设置过期时间为60秒
// 设置键的值和过期时间
redis.set(key, 'myvalue');
redis.expire(key, seconds);
// 自动刷新过期时间
setInterval(async () => {
const ttl = await redis.ttl(key);
if (ttl === -2) {
console.log('Key does not exist or has expired');
clearInterval(refreshInterval);
} else if (ttl === -1) {
console.log('Key exists and does not have an expiration');
} else {
console.log(`Refreshing expiration time: ${ttl} seconds left`);
redis.expire(key, seconds);
}
}, 5000); // 每5秒刷新一次过期时间
// 停止自动刷新过期时间
const refreshInterval = setInterval(() => {
clearInterval(refreshInterval);
}, 60000); // 60秒后停止自动刷新
In the example above, the value and expiration time of a key are initially set using the SET and EXPIRE commands. The setInterval timer is then used to refresh the expiration time, checking every 5 seconds if the key is still present and has remaining time. If the key exists and still has time remaining, a new expiration time is set using the EXPIRE command. The clearInterval function is used to stop the auto-refresh after 60 seconds.