Tokyo Tyrant(TTServer)系列-高可用性和高可靠性+nginx
1.基於memcache協議的高可用性
1.1構建一個互爲主輔的ttserver.
圖中構建了在ip爲177和178兩臺機器的互爲主輔結構的ttserver.
1.2在php中實現高可用
非常幸運,php的memcache客戶端直接就可以實現故障轉移的功能。其中的addServer函數或者方法非常好。
bool Memcache::addServer ( string $host [, int $port [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callback$failure_callback [, int $timeoutms ]]]]]]]] )
$memcache = new Memcache; $memcache->addServer('192.168.0.177', 11211); $memcache->addServer('192.168.0.178', 11211); $memcache->get("key"); ?> |
addServer 會把其中加入的ip放到一個池中,然後使用對鍵hash的方式(默認是crc32(key) % current_server_num)進行存取選擇服務器,當其中一臺服務器宕機不可用時,current_server_num就會減一,進行重新hash連接新的服務器,這樣就實現了故障的自動轉移。具體其中的原理可以查看php手冊中關於memcache部分。
1.3其他語言
http://code.google.com/p/memcached/wiki/Clients這是一個memcached的client API的各種語言實現的列表,幾乎所有的api都有提供php類似的addServer實現故障轉移功能。
2.利用nginx實現http協議的高可用性
2.1爲什麼要把nginx扯進來?
-
-
ttserver提供了http接口
-
ttserver沒有提供安全保證
-
nginx在處理http請求和反向代理的性能非常好
-
nginx的反向代理具有負載均衡和健康檢查功能
-
2.2如何結合nginx實現高可用性
2.2.1配置
在nginx配置文件中增加:
upstream backend {
server 192.168.0.177:11211 weight=5 max_fails=3 fail_timeout=30s;
server 192.168.2.178:11211 weight=1 max_fails=3 fail_timeout=30s;
}
|
利用upstream指向後端的兩臺機器。
location ~* /count(.*) {
if ($request_method = PUT ) {
return 403;
}
if ($request_method = DELETE ) {
return 403;
}
if ($request_method = POST ) {
return 403;
}
proxy_method GET;
proxy_pass http://backend;
} |
當路徑包含/count的時候,則代理到ttserver後端進行請求數據。請注意,這裏屏蔽了PUT,DELETE,POST方法,只是使用了GET,主要目的是爲了安全性,因爲DELETE,POST,PUT是可以修改數據的。
2.2.2使用
使用以上的配置文件,啓動nginx就可以訪問ttserver中的內容了。比如訪問http://host/count_key1將會顯示ttserver中key爲”count_key1”的內容。當我們不同時停掉177和178時,前端通過nginx http://host/count_key1都是同樣可以可用的。