一.需要先給nginx編譯第三方模組(ngx_http_consistent_hash) 1.下載ngx_http_consistent_hash-master,解壓
2.查看已安裝的nginx編譯參數:/usr/local/nginx/sbin/nginx -v
3.再nginx解壓目錄下面執行:./configure --prefix=/usr/local/nginx --add_module=/usr/local/src/ngx_http_consistent_hash-master/
(/usr/local/nginx:原nginx編譯好的路徑,usr/local/src/ngx_http_consistent_hash-master/:第三方模組目錄路徑)
4.因為已編譯的nginx可能在運行中:pkill -9 nginx
5. make && make install
二、配置memcache叢集
1.把用到的memcached節點,聲明在一個組裡
upstream memserver {
hash_key $request_uri; #hash計算時的依據,以uri做依據來hash
server localhost:11211;
server localhost:11212;
server localhost:11213;
}
2.location裡
location / {
set $memcached_key $uri;
memcached_pass memserver; #memserver為上面的memcache節點的名稱
error_page 404 /writemem.php;
}
3.重啟nginx:./sbin/nginx -s reload
4.開啟那3台memcache伺服器:
/usr/local/memcached/bin/memcached -u nobody -vv -p 11211
/usr/local/memcached/bin/memcached -u nobody -vv -p 11212
/usr/local/memcached/bin/memcached -u nobody -vv -p 11213
5.
上面是預設的負載平衡的演算法:是設定計數器,輪流請求N台伺服器。
我們要用安裝的第三方模組:(最上面安裝的)
如http://wiki.nginx.org/NginxHttpUpstreamConsistentHash
這個模組就是用一致性hash來請求後端結節,並且其演算法,與PHP中的memcache模組的一致性hash演算法,相容.
安裝該模組後,nginx.conf中:
upstream memserver {
consistent_hash $request_uri;
server 127.0.0.1:11211;
server 127.0.0.1:11212;
server 127.0.0.1:11213;
}
6.在php.ini中,如下配置:memcache.hash_strategy = consistent
這樣: nginx與PHP即可完成對memcached的叢集與負載平衡演算法.
殺死php進程:pkill -9 php-fpm
啟動php:/usr/local/php/sbin/php-fpm
7.writemem.php裡做寫入memcache的操作:
<?php
$uri = $_SERVER['REQUEST_URI']; //接收使用者查詢的key
//php也要添加和nginx一樣多的伺服器
$mem = new memcache();
$mem->addServer('127.0.0.1',11211);
$mem->addServer('127.0.0.1',11212);
$mem->addServer('127.0.0.1',11213);
//查詢資料庫
//todo...
//寫入memcached
$mem->add($url,'value',0,300);
$mem->close();
?>