HAProxy对redis和mysql服务实现四层负载

Posted y_zilong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HAProxy对redis和mysql服务实现四层负载相关的知识,希望对你有一定的参考价值。

haproxy的配置

注意:如果使用frontend和backend,一定在frontend和backend段中都指定mode tcp

[root@cen7_27 ~]# cat /etc/haproxy/conf.d/test.cfg 
listen web_port_80
   bind 10.0.0.27:80
   mode http
   balance roundrobin
   cookie WEBSRV insert nocache indirect
   server 10.0.0.40 10.0.0.40:80 check inter 3000 fall 2 rise 5 cookie web1
   server 10.0.0.50 10.0.0.50:80 check inter 3000 fall 2 rise 5 cookie web2

listen redis_port_6379
   bind 10.0.0.27:6379
   mode tcp
   balance leastconn
   server 10.0.0.40 10.0.0.40:6379 check    
   server 10.0.0.50 10.0.0.50:6379 check 

#使用frontend和backend实现
frontend mysql_port_3306
    bind :3306
    mode tcp                       #必须指定tcp模式
    default_backend mysql_port

backend mysql_port
    mode tcp                       #下面也必须使用tcp模式
    balance leastconn
    server 10.0.0.40 10.0.0.40:3306 check      #如果不写端口号,可以转发,但无法check
    server 10.0.0.50 10.0.0.50:3306 check
[root@cen7_27 ~]# 

[root@cen7_27 ~]# systemctl restart haproxy

在后端服务器安装和配置redis服务

[root@cent8_yzl_40 ~]# yum install -y redis
[root@cent8_yzl_40 ~]# sed -i '/^bind /c bind 0.0.0.0' /etc/redis.conf
[root@cent8_yzl_40 ~]# grep '^bind' /etc/redis.conf 
bind 0.0.0.0
[root@cent8_yzl_40 ~]# systemctl enable --now redis
[root@cent8_yzl_40 ~]# redis-cli set class 40
OK
[root@cent8_yzl_40 ~]# redis-cli get class
"40"
[root@cent8_yzl_40 ~]# 

在后端服务器安装和配置mariadb服务

[root@cent8_yzl_40 ~]# yum install -y mariadb-server
[root@cent8_yzl_40 ~]# systemctl enable --now mariadb

[root@cent8_yzl_40 ~]# mysql -e "grant all on *.* to test@'10.0.0.%' identified by 'redhat'"
[root@cent8_yzl_40 ~]# vim /etc/my.cnf

[mysqld]
server-id=40    #在另一台主机为50

[root@cent8_yzl_40 ~]# systemctl restart mariadb

#测试
[root@cent8_yzl_40 ~]# mysql -utest -predhat -h 10.0.0.40 -e 'select @@server_id'
+-------------+
| @@server_id |
+-------------+
|          40 |
+-------------+
[root@cent8_yzl_40 ~]# 

客户端测试

[root@cen7_17 ~]# yum install -y mariadb
[root@cen7_17 ~]# yum install -y redis
[root@cen7_17 ~]# redis-cli -h 10.0.0.27 get class
"50"
[root@cen7_17 ~]# redis-cli -h 10.0.0.27 get class
"40"
[root@cen7_17 ~]# mysql -utest -predhat -h 10.0.0.27 -e 'select @@server_id'
+-------------+
| @@server_id |
+-------------+
|          50 |
+-------------+
[root@cen7_17 ~]# mysql -utest -predhat -h 10.0.0.27 -e 'select @@server_id'
+-------------+
| @@server_id |
+-------------+
|          40 |
+-------------+
[root@cen7_17 ~]# 

以上是关于HAProxy对redis和mysql服务实现四层负载的主要内容,如果未能解决你的问题,请参考以下文章

HAProxy实现高级负载均衡实战和ACL控制

51-高性能负载均衡应用Haproxy-安装及配置案例

HAPROXY实战案例:https反向代理的实现TCP四层反向代理MariaDB及自定义错误页面

HAProxy后端web服务器状态检测

项目实战4—haproxy 负载均衡和ACL控制

HAproxy七层负载均衡四层/七层负载均衡