在 Node.js 中使用 Redis 存储验证码并进行持久化存储可以使用以下代码:

const redis = require('redis');
const { promisify } = require('util');

const client = redis.createClient();

// 将 Redis 的 set 方法转换为 Promise
const setAsync = promisify(client.set).bind(client);

// 设置验证码并且设置过期时间为 5 分钟
async function setVerificationCode(key, value) {
  await setAsync(key, value, 'EX', 300); // EX 参数表示设置过期时间,300 表示 5 分钟
}

// 获取验证码
async function getVerificationCode(key) {
  const value = await client.get(key);
  return value;
}

在上述代码中,使用了 Redis 的 'set' 方法将验证码存储到 Redis 中,并使用 'EX' 参数设置了过期时间。'promisify' 方法将 Redis 的 'set' 方法转换为 Promise,以便可以使用 'async/await' 语法进行调用。

当设置的过期时间到期后,Redis 会自动将内存中存储的验证码删除,无需手动删除。

'client.set' 方法的原理是将键值对存储到 Redis 的内存中,如果设置了过期时间,Redis 会在过期时间到期后自动删除键值对。如果未设置过期时间,键值对将一直存储在 Redis 中。

Node.js 使用 Redis 存储验证码:持久化、过期时间及原理

原文地址: https://www.cveoy.top/t/topic/mvcH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录