【发布时间】:2013-03-11 10:57:57
【问题描述】:
我的任务是为一个客户处理一个项目,该客户拥有一个他估计每天将获得 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:节点写入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:前面清漆
我做了一些研究和基准测试,就像本网站上显示的那样,让我远离这个解决方案,但如果它最有意义,我仍然愿意考虑它:http://todsul.com/nginx-varnish
【问题讨论】:
-
我们需要知道您服务的唯一页面数量以及您服务的页面的哪些部分是可缓存的。例如,如果每个页面都显示用户名和当前时间(不使用 JavaScript 更新它),那么任何页面都不能被缓存,因为每个人看到的页面不同。即使每个人在同一个 URL 上看到同一个页面,如果您的站点有数百万个(自动生成的)页面,以至于一天中 95% 的页面只被查看一次,那么再次缓存也无济于事。因此,我们需要有关您的情况的更多信息。
标签: node.js caching nginx redis varnish