天天看點

Memcache分布式部署方案

前言

同時在百度和Google,關鍵詞Memcache在長達一年多的時間裡占據着第二位(第一位是官方),為很多需要了解或者應用Memcache的朋友提供了一些資訊,但是我始終覺着還不夠,于是本文誕生。

唠唠叨叨說了半天,如果你覺着前面啰嗦,請直接看最後一大段,那是本文的重點。

基礎環境

其實基于PHP擴充的Memcache用戶端實際上早已經實作,而且非常穩定。先解釋一些名詞,Memcache是danga.com的一個開源項目,可以類比于MySQL這樣的服務,而PHP擴充的Memcache實際上是連接配接Memcache的方式。

首先,進行Memcache被安裝具體可檢視:

其次,進行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

/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的分布式部署,是不是非常簡單。

分布式系統的良性運作

修改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