Skip to content

MySQL/PostgreSQL 数据库负载均衡

HAProxy 可作为数据库的负载均衡器,支持读写分离、分片和连接池管理。

MySQL 基础配置

haproxy
backend mysql_cluster
    mode tcp
    balance leastconn
    option mysql-check inter 2000 rise 2 fall 3
    server mysql1 10.0.0.11:3306 maxconn 200 check port 3306
    server mysql2 10.0.0.12:3306 maxconn 200 check port 3306 backup

创建健康检查用户

sql
CREATE USER haproxy_check@%;
GRANT USAGE ON *.* TO haproxy_check@%;

读写分离

haproxy
frontend mysql_front
    bind *:3306
    mode tcp
    acl is_read query SQL_SELECT
    use_backend mysql_read if is_read
    use_backend mysql_write if !is_read

PostgreSQL 配置

haproxy
backend postgres_cluster
    mode tcp
    balance leastconn
    option pgsql-check user haproxy_check
    server pghost1 10.0.0.21:5432 maxconn 100 check