使用 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
相关推荐
q***96583 分钟前
如何在 Ubuntu 22.04 上安装 MySQL
linux·mysql·ubuntu
高铭杰3 小时前
mysql主备配置(对比postgresql)
数据库·mysql·replication
~~李木子~~8 小时前
MySQL 迁移总结报告
数据库·mysql
CodeLongBear9 小时前
MySQL索引篇 -- 从数据页的角度看B+树
mysql·面试
桦09 小时前
MySQL【函数】
数据库·mysql
_Minato_11 小时前
数据库知识整理——SQL数据定义
数据库·sql·mysql·oracle·database·数据库开发·数据库架构
程序员卷卷狗11 小时前
MySQL 四种隔离级别:从脏读到幻读的全过程
数据库·mysql
IT教程资源D12 小时前
[N_148]基于微信小程序网上书城系统
mysql·vue·uniapp·前后端分离·网上书城小程序·springboot书城
友友马14 小时前
『 数据库 』MySQL索引深度解析:从数据结构到B+树的完整指南
数据库·mysql
IT教程资源D14 小时前
[N_151]基于微信小程序校园学生活动管理平台
mysql·校园活动小程序·springboot校园活动