使用 HAProxy 进行 MySQL 负载均衡

本章教程主要记录如何用HAProxy 实现MySQL负载均衡配置。

一、安装haproxy

在 Ubuntu/Debian 上:

bash 复制代码
sudo apt-get update
sudo apt-get install haproxy

在 CentOS/RHEL 上:

bash 复制代码
sudo yum install haproxy

二、配置haproxy

编辑 HAProxy 配置文件(通常位于 /etc/haproxy/haproxy.cfg)。

bash 复制代码
#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   https://www.haproxy.org/download/1.8/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    log         127.0.0.1 local2

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

    # utilize system-wide crypto-policies
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                    tcp
    log                     global
    option                  tcplog
    option                  dontlognull
    option                  redispatch
    retries                 3
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    maxconn                 3000

#---------------------------------------------------------------------
# MySQL frontend and backend configuration
#---------------------------------------------------------------------
frontend mysql_frontend
    bind *:3308
    default_backend mysql_backend

backend mysql_backend
    balance roundrobin
    server mysql1 172.19.0.2:3306 check
    server mysql2 172.19.0.3:3306 check

三、启动/重启/停止haproxy

1、启动haproxy

bash 复制代码
sudo systemctl start haproxy

2、重启haproxy

bash 复制代码
sudo systemctl restart haproxy

3、停止haproxy

bash 复制代码
sudo systemctl restart haproxy
相关推荐
小王努力学编程7 小时前
【MySQL篇】表的操作
数据库·mysql
汤汤upup7 小时前
面试八股文--数据库基础知识总结(2) MySQL
数据库·mysql·面试
TangKenny7 小时前
information_schema.processlist 表详解
mysql·processlist
m0_7482509310 小时前
mysql数据被误删的恢复方案
数据库·mysql
m0_7482384210 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
一小路一10 小时前
从0-1学习Mysql第五章: 索引与优化
数据库·后端·学习·mysql·面试
彤彤的小跟班11 小时前
MySQL进阶04-MVCC实现原理
数据库·mysql
huaqianzkh12 小时前
基于 ‌MySQL 数据库‌对三级视图(用户视图、DBA视图、内部视图)的详细解释
数据库·mysql·dba
ForTodayzzZ12 小时前
centos和ubuntu安装mysql教程
linux·mysql·ubuntu·centos
扣丁梦想家13 小时前
《Spring Boot + MySQL高性能应用实战:性能优化技巧与最佳实践》
spring boot·后端·mysql