MST

星途 面试题库

面试题:Node.js Express性能调优之缓存策略

在Node.js的Express应用中,为了提升性能,经常会使用缓存策略。请阐述在Express框架下,你会如何实现页面级缓存和数据级缓存?分别列举至少一种常用的缓存技术或模块,并说明它们的基本使用方法。
19.2万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试

页面级缓存

常用技术或模块:express - cache - response

  1. 安装
    npm install express - cache - response
    
  2. 基本使用方法
    const express = require('express');
    const cache = require('express - cache - response');
    const app = express();
    
    app.get('/cached - page', cache({
        statusCode: 200,
        duration: 60 * 1000, // 缓存1分钟
        etag: true
    }), (req, res) => {
        res.send('This is a cached page');
    });
    
    const port = 3000;
    app.listen(port, () => {
        console.log(`Server running on port ${port}`);
    });
    
    • 此模块会根据设置的duration时间对响应进行缓存,在缓存时间内,相同请求会直接返回缓存内容,提高响应速度。etag选项用于启用ETag头生成,有助于缓存控制。

数据级缓存

常用技术或模块:node - cache

  1. 安装
    npm install node - cache
    
  2. 基本使用方法
    const express = require('express');
    const NodeCache = require('node - cache');
    const app = express();
    const myCache = new NodeCache();
    
    app.get('/cached - data', (req, res) => {
        const cachedData = myCache.get('my - data - key');
        if (cachedData) {
            return res.json(cachedData);
        }
        const newData = { message: 'This is newly fetched data' };
        myCache.set('my - data - key', newData);
        res.json(newData);
    });
    
    const port = 3000;
    app.listen(port, () => {
        console.log(`Server running on port ${port}`);
    });
    
    • 先尝试从缓存中获取数据,如果存在则直接返回。若不存在,获取新数据,存入缓存并返回。这样对于频繁请求的数据,可减少重复获取数据的开销,提升性能。