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都是同样可以可用的。