consistencehash
https://github.com/replay/ngx_http_consistent_hash->download
https://github.com/replay/ngx_http_consistent_hash/archive/master.zip
[root@localhost soft]# wget https://github.com/replay/ngx_http_consistent_hash/archive/master.zip
[root@localhost soft]# unzip master
[root@localhost soft]# cd ngx_http_consistent_hash-master#readme
[root@localhost ngx_http_consistent_hash-master]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.4.2
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)
configure arguments: --prefix=/usr/local/nginx
[root@localhost soft]# cd nginx-1.4.2
[root@localhost nginx-1.4.2]# ls
auto CHANGES.ru configure html Makefile objs src
CHANGES conf contrib LICENSE man README
[root@localhost nginx-1.4.2]# ./configure --prefix=/usr/local/nginx --add-module=/root/soft/ngx_http_consistent_hash-master/
[root@localhost nginx-1.4.2]# make &&make install
cd nginx
[root@localhost nginx]# cd sbin
[root@localhost sbin]# ./nginx
upstream memserver {
server localhost:11211;
server localhost:11212;
server localhost:11213;
}
location / {
# root html;
set $memcached_key $uri;
memcached_pass memserver; // memserver为上面的memcache节点的名称
error_page 404 /writemem.php;
index index.php index.html index.htm;
}
[root@localhost nginx]# /usr/local/bin/memcached -u nobody -vv
[root@localhost nginx]# /usr/local/bin/memcached -u nobody -vv -p 11212
[root@localhost nginx]# /usr/local/bin/memcached -u nobody -vv -p 11213
访问urlhttp://192.168.88.156/use5.html
<7 get /use5.html
>7 END
<7 connection closed.
[root@localhost nginx]# vi conf/nginx.conf
upstream memserver {
consistent_hash $request_uri;#在一台上访问
server localhost:11211;
server localhost:11212;
server localhost:11213;
}
root@localhost nginx]# ./sbin/nginx -s reload
添加多台服务器
php也要添加和nginx同样多的服务器
$mem=new memcache();
$mem->addServer('localhost',11211);
$mem->addServer('localhost',11212);
$mem->addServer('localhost',11213);
修改php.ini
vim /usr/local/fastphp/lib/php.ini
memcache.hash_strategy=consistent
pkill -9 php-fpm
/usr/local/fastphp/sbin/php-fpm
大量访问量优化总体思路
1.减小请求, expires利用浏览器缓存减小查询
2.合并css背景图片减小mysql查询
3.利用cdn响应请求
4.最终剩下的,不可避免的请求,--服务集群+负载均衡来支撑
配置memcache集群
upstream memserver { 把用到的memcached节点,声明在一个组里
hash_key $request_uri; // hash计算时的依据,以uri作依据来hash
server localhost:11211;
server localhost:11212;
}
Location里
location / {
# root html;
set $memcached_key $uri;
memcached_pass memserver; // memserver为上面的memcache节点的名称
error_page 404 /writemem.php;
index index.php index.html index.htm;
}
在nginx中作集群与负载均衡,步骤都是同样的
Upstream {}模块 把多台服务器加入到一个组
而后 memcached_pass, fastcgi_pass, proxy_pass ==> upstream组
默认的负载均衡的算法:
是设置计数器,轮流请求N台服务器.
能够安装第3方模式,来利用uri作hash等等.
如http://wiki.nginx.org/NginxHttpUpstreamConsistentHash
这个模块就是用一致性hash来请求后端结节,而且其算法,与PHP中的memcache模块的一致性hash算法,兼容.
安装该模块后:
Nginx.conf中
upstream memserver {
consistent_hash $request_uri;
server localhost:11211;
server localhost:11212;
}
在PHP.ini中,以下配置
memcache.hash_strategy = consistent
这样: nginx与PHP便可完成对memcached的集群与负载均衡算法.
php