node.js - node.js/nginx 是否对常用文件使用内部缓存?

标签 node.js caching

我想知道 node.js 是否正在为以下场景使用缓存,或者是否存在用于该场景的模块:

例如,如果您有一个 Web 门户网站,它在首页显示 20 个带有图像的产品,每次服务器都必须从 hdd 或最好的情况下从 ssd 获取图像。 对于每个单独的图像,服务器需要大约 5-7 毫秒。当您有 50 个用户同时访问起始页时,需要 20img * 5ms * 50 usr = 5000ms 才能在硬盘上找到图像。

因此,如果有一种方法可以将所有常用文件(如图像、css、html 等)保存在内存中,那就太好了。所以您只需定义缓存大小即可。例如 50MB 和 module/node.js 将经常使用的文件保留在缓存中。

最佳答案

Node.js 本身(默认情况下)不做任何缓存,尽管操作系统和其他较低层元素(例如 HDD)可能会做,从而显着加快连续读取。

如果你想在 nodejs 中启用缓存的 http 响应,有一个 http-cache 库 - https://www.npmjs.com/package/http-cacherequest-caching 库 - https://www.npmjs.com/package/node-request-caching .对于缓存文件,您可以使用 filecache https://www.npmjs.com/package/filecache并用于提供静态文件 - serve-static ( https://www.npmjs.com/package/serve-static )。

如果您使用的是 Express 等框架,那就不再那么简单了 - 例如,在生产模式下运行 Express 会导致它缓存一些内容(如模板或 CSS)。另请注意,res.sendFile 将文件直接流式传输给客户(可能是代理服务器,例如 nginx)

但是,即使是 Express 的网页(http://expressjs.com/en/advanced/best-practice-performance.html)也建议使用单独的代理:

Cache request results

Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.

Use a caching server like Varnish or Nginx (see also Nginx Caching) to greatly improve the speed and performance of your app.

有关加速 nodejs 的其他建议,您可以查看 https://engineering.gosquared.com/making-dashboard-fasterhttp://www.sitepoint.com/10-tips-make-node-js-web-app-faster/

关于node.js - node.js/nginx 是否对常用文件使用内部缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36480513/

相关文章:

ruby-on-rails - 关于这个 Varnish VCL 的几个问题

node.js - 添加到 JSON 的新数据不断替换以前的数据

javascript - 如何将 Json 数组转换为 vis.dataset

node.js - (Chai) assert.isBoolean 不是一个函数——我做错了什么?

http - 为什么浏览器不遵守 Cache-Control header ?

php - ob_start 缓存 CSS

javascript - Service Worker 不适用于移动网络(Chrome、Firefox、IE)

javascript - yarn 2 : Difference between Zero Installs and normal install?

Node.js 将自定义对象序列化/反序列化到 mongodb

linux - 在回收之前写入缓存页面