HaProxy实现Mongos负载均衡

前言

连接到分片集群的方式和连接到普通MongoDB实例的方式完全相同,不过当存在多个mongos实例的情况下,即使URI里写全了mongos实例的IP也无法自动做到mongos本身的高可用和负载均衡,通常这个可以通过搭建HaProxy或者LVS的方式实现。

实验条件

假设存在三个mongos节点,分别为10.9.71.164,10.9.69.74,10.9.77.132,而HaProxy的代理IP为10.9.80.23,采用简单的roundrobin轮询策略,则连接URI举例如下

mongodb://uclouder:edFO09SkdU@IP4:27017/test? 

如何搭建haproxy不做描述,haproxy的配置文件如下


#---------------------------------------------------------------------
global
    
    log         127.0.0.1 local3
   chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        root 
    group       root 
    daemon


    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats
#---------------------------------------------------------------------
defaults
log global
mode tcp
option tcplog
option dontlognull
retries 3
#redispatch
maxconn 6000
        balance roundrobin 
#---------------------------------------------------------------------
listen  ha-proxy 10.9.80.23:27017
timeout connect 10s
        timeout client 8h
        timeout server 8h
mode  tcp
option tcp-check
        #option mysql-check user haproxy
server  10.9.71.164 10.9.71.164:27017 check port 27017 inter 2s rise 1 fall 6
server  10.9.69.74 10.9.69.74:27017 check port 27017 inter 2s rise 1 fall 6
                 server 10.9.77.132 10.9.77.132:27017 check port 27017 inter 2s rise 1 fall 6

测试方法

挨个用mongo shell客户端连接mongos,连一次断一次,通过haproxy的日志分析轮询结果

./mongo 10.9.80.23:27017/test -ujiang -pjiangshan

haproxy日志如下,可见实现了mongos的负载均衡


Aug  1 20:42:30 localhost haproxy[4192]: Proxy ha-proxy started.
Aug  1 20:51:33 localhost haproxy[4193]: 10.9.80.23:47939 [01/Aug/2016:20:51:15.168] ha-proxy ha-proxy/10.9.71.164 1/0/18007 2253 -- 0/0/0/0/0 0/0
Aug  1 20:51:55 localhost haproxy[4193]: 10.9.80.23:48001 [01/Aug/2016:20:51:55.157] ha-proxy ha-proxy/10.9.69.74 1/0/557 983 -- 0/0/0/0/0 0/0
Aug  1 20:52:04 localhost haproxy[4193]: 10.9.80.23:48016 [01/Aug/2016:20:52:04.253] ha-proxy ha-proxy/10.9.77.132 1/0/513 983 -- 0/0/0/0/0 0/0
Aug  1 20:52:19 localhost haproxy[4193]: 10.9.80.23:48038 [01/Aug/2016:20:52:17.694] ha-proxy ha-proxy/10.9.71.164 1/0/1902 983 -- 0/0/0/0/0 0/0
Aug  2 10:53:05 localhost haproxy[4193]: 74.82.47.4:56199 [02/Aug/2016:10:53:05.436] ha-proxy ha-proxy/10.9.69.74 1/0/296 803 -- 0/0/0/0/0 0/0
Aug  2 10:53:26 localhost haproxy[4193]: 74.82.47.4:37346 [02/Aug/2016:10:53:26.029] ha-proxy ha-proxy/10.9.77.132 1/0/251 139 -- 0/0/0/0/0 0/0
Aug  3 13:26:02 localhost haproxy[4193]: 216.218.206.66:33344 [03/Aug/2016:13:25:50.809] ha-proxy ha-proxy/10.9.71.164 1/-1/11413 0 SC 0/0/0/0/3 0/0

你可能感兴趣的:(NoSQL/MongoDB)