Memcache分佈式部署方案

基礎環境
其實基於PHP擴展的Memcache客戶端實際上早已經實現,並且很是穩定。先解釋一些名詞,Memcache是danga.com的一個開源項目,能夠類比於MySQL這樣的服務,而PHP擴展的Memcache其實是鏈接Memcache的方式。
首先,進行Memcache被安裝具體可查看:
Linux下的Memcache安裝:http://www.ccvita.com/257.html
Windows下的Memcache安裝:http://www.ccvita.com/258.html;
其次,進行PHP擴展的安裝,官方地址是http://pecl.php.net/package/memcache
最後,啓動Memcache服務,好比這樣
/usr/local/bin/memcached -d -p 11213 -u root -m 10 -c 1024 -t 8 -P /tmp/memcached.pid
/usr/local/bin/memcached -d -p 11214 -u root -m 10 -c 1024 -t 8 -P /tmp/memcached.pid
/usr/local/bin/memcached -d -p 11215 -u root -m 10 -c 1024 -t 8 -P /tmp/memcached.pid
啓動三個只使用10M內存以方便測試。
分佈式部署
PHP的PECL擴展中的memcache實際上在2.0.0的版本中就已經實現多服務器支持,如今都已經2.2.5了。請看以下代碼
$memcache = new Memcache;
$memcache->addServer('localhost', 11213);
$memcache->addServer('localhost', 11214);
$memcache->addServer('localhost', 11215);
$memStats = $memcache->getExtendedStats();
print_r($memStats);
經過上例就已經實現Memcache的分佈式部署,是否是很是簡單。
分佈式系統的良性運行
在Memcache的實際使用中,遇到的最嚴重的問題,就是在增減服務器的時候,會致使大範圍的緩存丟失,從而可能會引導數據庫的性能瓶頸,爲了不出現這種狀況,請先看 Consistent hashing算法,中文的介紹能夠參考 這裏,經過存取時選定服務器算法的改變,來實現。
修改PHP的Memcache擴展memcache.c的源代碼中的
"memcache.hash_strategy" = standard
"memcache.hash_strategy" = consistent
從新編譯,這時候就是使用Consistent hashing算法來尋×××器存取數據了。
有效測試數據代表,使用Consistent hashing能夠極大的改善增刪Memcache時緩存大範圍丟失的狀況。 NonConsistentHash: 92% of lookups changed after adding a target to the existing 10 NonConsistentHash: 90% of lookups changed after removing 1 of 10 targets ConsistentHash: 6% of lookups changed after adding a target to the existing 10 ConsistentHash: 9% of lookups changed after removing 1 of 10 targets