如何在Nodejs中使用缓存

如何在Nodejs中使用缓存

很简单的一个应用场景,往缓存中写入一个随机的字符串用来做验证,一天后过期。 在Nodejs中,必须要使用类似redis这类东西才能搞定吗?

4 回复

当然不是!在Node.js中实现简单的缓存功能并不一定需要依赖外部工具如Redis。你可以使用内置的模块或者简单的内存对象来实现基本的缓存功能。下面将介绍几种不同的方法来实现缓存。

方法1:使用内存对象

最简单的方法就是直接在内存中存储数据。这种方法适合于不需要持久化存储且应用不频繁重启的场景。

const express = require('express');
const app = express();

// 使用一个简单的内存对象作为缓存
let cache = {};

function setCache(key, value, ttl) {
    cache[key] = { value, ttl: Date.now() + ttl };
}

function getCache(key) {
    const entry = cache[key];
    if (entry && entry.ttl >= Date.now()) {
        return entry.value;
    }
    delete cache[key]; // 清除过期条目
    return null;
}

app.get('/set-cache', (req, res) => {
    const randomString = Math.random().toString(36).substring(2, 15);
    setCache('randomString', randomString, 86400 * 1000); // 设置缓存有效期为一天(毫秒)
    res.send('缓存已设置');
});

app.get('/get-cache', (req, res) => {
    const cachedValue = getCache('randomString');
    if (cachedValue) {
        res.send(`从缓存获取的值: ${cachedValue}`);
    } else {
        res.send('未找到缓存或缓存已过期');
    }
});

app.listen(3000, () => console.log('服务器运行在 http://localhost:3000'));

方法2:使用第三方库

对于更复杂的场景,可以考虑使用像 node-cache 这样的第三方库,它提供了更高级的功能,如自动过期、事件监听等。

首先安装 node-cache

npm install node-cache

然后使用它:

const NodeCache = require("node-cache");
const myCache = new NodeCache({stdTTL: 86400, checkperiod: 120});

app.get('/set-cache', (req, res) => {
    const randomString = Math.random().toString(36).substring(2, 15);
    myCache.set("randomString", randomString);
    res.send('缓存已设置');
});

app.get('/get-cache', (req, res) => {
    const cachedValue = myCache.get("randomString");
    if (cachedValue) {
        res.send(`从缓存获取的值: ${cachedValue}`);
    } else {
        res.send('未找到缓存或缓存已过期');
    }
});

以上两种方法都可以满足你需求中的场景,选择哪种取决于你的具体需求和项目的复杂度。


无论什么语言,把它放在redis/memcached等缓存里都是最好的选择,专人干专事,各施其责

看场景,如果不怕重启丢失和内存占用,直接放内存都行。根据实际需求,定吧。

在Node.js中使用缓存并不一定非要用如Redis这样的外部存储。你可以选择多种方式来实现缓存功能,例如内存缓存、文件系统缓存等。以下是一些常见的缓存方案及其示例代码。

1. 使用内存缓存(Memory Cache)

使用内存缓存是最简单的方式之一。你可以直接使用JavaScript对象或Map来存储数据,并设置过期时间。但这种方式在服务器重启时缓存会丢失。

示例代码:

const express = require('express');
const app = express();
const randomstring = require("randomstring");

let cache = new Map();

function setCache(key, value, ttl) { // ttl为存活时间,单位是毫秒
    const now = Date.now();
    cache.set(key, { value, expiresAt: now + ttl });
}

function getCache(key) {
    if (cache.has(key)) {
        const item = cache.get(key);
        if (Date.now() < item.expiresAt) {
            return item.value;
        } else {
            cache.delete(key); // 如果已过期则删除
        }
    }
    return null;
}

app.get('/generate-verification-code', (req, res) => {
    const key = 'myVerificationCode';
    let code = getCache(key);
    if (!code) {
        code = randomstring.generate(6);
        setCache(key, code, 24 * 60 * 60 * 1000); // 缓存一天
    }
    res.send(code);
});

app.listen(3000, () => console.log('Server running on port 3000'));

2. 使用第三方缓存库(如node-cache

你可以使用一些现成的库,如node-cache,它提供了更简单的API来处理缓存和过期机制。

安装:

npm install node-cache

示例代码:

const NodeCache = require("node-cache");
const myCache = new NodeCache({ stdTTL: 24 * 60 * 60, checkperiod: 120 });

const express = require('express');
const app = express();
const randomstring = require("randomstring");

app.get('/generate-verification-code', (req, res) => {
    const key = 'myVerificationCode';
    let code = myCache.get(key);
    if (!code) {
        code = randomstring.generate(6);
        myCache.set(key, code);
    }
    res.send(code);
});

app.listen(3000, () => console.log('Server running on port 3000'));

以上两种方法都可以满足你的需求,选择哪种取决于你的具体场景和性能要求。如果需要持久化存储,可以考虑使用Redis等分布式缓存服务。

回到顶部