nginx與PHP使用一致性雜湊演算法對memcached的叢集與負載平衡

來源:互聯網
上載者:User


一.需要先給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();
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.