在Node.js中,缓存机制的应用非常广泛,可以显著提高应用程序的性能和响应速度。以下是一些常见的缓存应用方式:
npm包缓存:
Node.js应用程序缓存:
lru-cache模块,例如:const LRU = require('lru-cache');
const cache = new LRU({ max: 500, maxAge: 1000 * 60 * 60 }); // 500 items, 1 hour TTL
cache.set('key', 'value');
const value = cache.get('key');
node-cache模块,例如:const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 3600, checkperiod: 600 }); // 1 hour TTL, check every 10 minutes
cache.set('key', 'value', (err, success) => {
if (err) console.error(err);
else console.log(success);
});
const value = cache.get('key');
const Redis = require('ioredis');
const redis = new Redis();
redis.set('key', 'value');
const value = redis.get('key', (err, value) => {
if (err) console.error(err);
else console.log(value);
});
数据库数据缓存:
node-cache或memory-cache)或分布式缓存(如Redis),例如:const NodeCache = require('node-cache');
const cache = new NodeCache();
cache.set('key', 'value', 1000); // 缓存1秒
const value = cache.get('key');
HTTP缓存控制:
Cache-Control、ETag、Last-Modified等字段来控制缓存,例如:const express = require('express');
const app = express();
app.get('/data', (req, res) => {
const data = { message: 'Hello, World!' };
res.set('Cache-Control', 'public, max-age=300'); // 缓存300秒
res.set('ETag', 'unique-etag-value'); // 设置ETag
res.set('Last-Modified', new Date().toUTCString()); // 设置最后修改时间
res.json(data);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
页面缓存:
const express = require('express');
const app = express();
app.get('/page', (req, res) => {
const cacheKey = 'pageCacheKey';
const cachedData = cache.get(cacheKey); // 假设使用内存缓存
if (cachedData) {
return res.send(cachedData);
}
const pageContent = generatePageContent(); // 生成页面内容的函数
cache.set(cacheKey, pageContent, 60); // 缓存60秒
res.send(pageContent);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。