如何配置 HaProxy 以平衡对 PostgreSQL 集群所有节点的读取请求?

How to configure HaProxy to balance read requests to all nodes of a PostgreSQL cluster?

我在 Patroni (Haproxy+Keepalived+etcd) 上有一个 PostgreSQL 集群 - 一个主节点和两个备用节点。

目前,Haproxy 配置如下:

如何配置 Haproxy 以便端口 5001 用于连接备用节点和主节点?

下面是我的haproxy.cfg

global
maxconn 1000
nbproc 2

defaults
log global
mode tcp
retries 2
timeout client 30m
timeout connect 4s
timeout server 30m
timeout check 5s

listen stats
  mode http
  bind *:7000
  stats enable
  stats uri /

frontend ft_postgresql
bind *:5000
default_backend postgres-patroni

frontend ft_postgresql_replica
bind *:5001
default_backend postgres-patroni-replica

backend postgres-patroni
  option httpchk OPTIONS /master

  http-check expect status 200
  default-server inter 3s fall 3 rise 2

  server node_one ip.to.node.one:5432 maxconn 1000 check port 8008 on-marked-down shutdown-sessions
  server node_two ip.to.node.two:5432 maxconn 1000 check port 8008 on-marked-down shutdown-sessions
  server node_three ip.to.node.three:5432 maxconn 1000 check port 8008 on-marked-down shutdown-sessions

backend postgres-patroni-replica
  option httpchk OPTIONS /replica

  http-check expect status 200
  default-server inter 3s fall 3 rise 2

  server node_one ip.to.node.one:5432 maxconn 1000 check port 8008 on-marked-down shutdown-sessions
  server node_two ip.to.node.two:5432 maxconn 1000 check port 8008 on-marked-down shutdown-sessions
  server node_three ip.two.node.three:5432 maxconn 1000 check port 8008 on-marked-down shutdown-sessions

在 patroni 文档中我找到了 /health 端点 patroni rest-api:

returns HTTP status code 200 only when PostgreSQL is up and running.

我尝试在 haproxy 配置中使用该端点,它按预期工作,当所有节点都处于活动状态时,赞助人会提供所有 3 个节点,并且不提供不在 运行 状态的节点

因此,如果要将所有节点添加到 haproxy 余额中,请在 haproxy.conf

中创建一个新后端
backend postgres-patroni-all
  option httpchk OPTIONS /health

  http-check expect status 200
  default-server inter 3s fall 3 rise 2

  server node_one ip.to.node.one:5432 maxconn 1000 check port 8008 on-marked-down shutdown-sessions
  server node_two ip.to.node.two:5432 maxconn 1000 check port 8008 on-marked-down shutdown-sessions
  server node_three ip.two.node.three:5432 maxconn 1000 check port 8008 on-marked-down shutdown-sessions

以及此后端的前端,例如在 5002 端口:

frontend ft_postgresql_all
bind *:5002
default_backend postgres-patroni-all