node.js - 对于 Node/Mongo/NginX,哪种缓存方法最快/最轻?

标签 node.js caching nginx redis varnish

我的任务是为一个客户开展一个项目,该客户拥有一个他估计每天将获得 1-2M 次点击的网站。他拥有一个包含 5800 万用户的现有数据库,这些用户需要在每次注册的基础上为新品牌播种。该网站的大部分内容都是由外部 API 提供的数据提供的,其中存储在我们的 Mongo 设置中的大部分数据是配置文件信息和保存的 API 参数。

NginX 将在端口 80 上,并在端口 8000 - 8010 上对 Node 集群进行负载平衡。

我的问题是如何处理缓存。我来自 LAMP 背景,所以我习惯于使用 PHP 编写静态 HTML 文件并提供这些文件以最小化 MySQL 负载,或者将 Memcached 用于需要更高级别缓存的站点。这个设置对我来说有点陌生。

最小响应时间和 CPU 负载而言,哪个最理想?

1:使用 NginX 进行页面级缓存

引用:http://andytson.com/blog/2010/04/page-level-caching-with-nginx/

server {
    listen            80;
    servername        mysite.com;

    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  Host       $host;

    location / {
        proxy_pass    http://localhost:8080/;
        proxy_cache   anonymous;
    }

    # don't cache admin folder, send all requests through the proxy
    location /admin {
        proxy_pass    http://localhost:8080/;
    }

    # handle static files directly. Set their expiry time to max, so they'll
    # always use the browser cache after first request
    location ~* (css|js|png|jpe?g|gif|ico)$ {
        root          /var/www/${host}/http;
        expires       max;
    }
}


2:Redis 作为缓存桶

hash() 函数就是本页的numbers() 函数:http://jsperf.com/hashing-strings

function hash(str) {
    var res = 0,
        len = str.length;
    for (var i = 0; i < len; i++) {
        res = res * 31 + str.charCodeAt(i);
    }
    return res;
}

var apiUrl = 'https://www.myexternalapi.com/rest/someparam/someotherparam/?auth=3dfssd6s98d7f09s8df98sdef';
var key    = hash(apiUrl).toString(); // 1.8006908172911553e+136

myRedisClient.set(key,theJSONresponse, function(err) {...});


3: Node 写入JSON文件

hash() 函数就是本页的numbers() 函数:http://jsperf.com/hashing-strings

function hash(str) {
    var res = 0,
        len = str.length;
    for (var i = 0; i < len; i++) {
        res = res * 31 + str.charCodeAt(i);
    }
    return res;
}

var fs     = require('fs');
var apiUrl = 'https://www.myexternalapi.com/rest/someparam/someotherparam/?auth=3dfssd6s98d7f09s8df98sdef';
var key    = hash(apiUrl).toString(); // 1.8006908172911553e+136

fs.writeFile('/var/www/_cache/' + key + '.json', theJSONresponse, function(err) {...});


4:前面 Varnish

我做了一些研究和基准测试,例如本网站上显示的基准测试,这让我远离了这个解决方案,但如果它最有意义,我仍然愿意考虑它:http://todsul.com/nginx-varnish

最佳答案

我会做一个组合,使用 Redis 缓存具有短 TTL 的 session 用户 API 调用,并使用 Nginx 缓存长期 RESTless 数据和静态 Assets 。我不会编写 JSON 文件,因为我认为文件系统 IO 将是列出的选项中最慢且 CPU 密集度最高的选项。

关于node.js - 对于 Node/Mongo/NginX,哪种缓存方法最快/最轻?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15555896/

相关文章:

node.js - 迁移到 ES6

ubuntu - 在 nGinX 上安装 php 后 phpinfo() 工作但没有别的

apache - 从多个 tomcat 网站的 url 隐藏名称和端口

html - 多个表行名称属性到 json 数组

node.js - Express + JWT 排除某些路由

javascript - 如何根据数字显示评分

django - 权限被拒绝 - nginx 和 uwsgi 套接字

ruby-on-rails - 使用延迟作业的页面缓存

php - 如何清除redis中键的值

php - 在 laravel 中全局缓存表值