Haproxy 平衡。如何在 haproxy 检查器中找到最小值?

Haproxy Balancing. How to find the minimum value in a haproxy checker?

我正在尝试配置 Haproxy 以在 postgres 副本之间进行平衡。 主要任务:请求应该被重定向到具有最新数据的节点。 检查数据相关性运行于 master_node:

select client_addr AS client, (pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn))::int / 1024 as total_lag from pg_stat_replication;

使用此命令,我获得了主机列表和 replication_lag。 例如:

111.111.111.111 | 152
222.222.222.222 | 9
333.333.333.333 | 4700

我需要一个最小值的主机。 我不明白三件事:

  1. 如何将副本名称传递给自定义 haproxy_checker?
  2. 如何比较得到的值?
  3. haproxy如何根据给定的值指定请求切换到哪个replicas?

我应用了这些设置: haproxy.cfg

lua-load /etc/haproxy/scripts/choosebackend.lua

frontend psql-front
bind *:5432
mode tcp
use_backend %[lua.choose_backend]

backend backend1
mode tcp
balance roundrobin
server pg1 111.111.111.111:5432 check port 5432

backend backend2
mode tcp
balance roundrobin
server pg2 222.222.222.222:5432 check port 5432

choosebackend.lua

luasql = require "luasql.postgres"
env = luasql.postgres()
con = assert (env:connect('postgres', 'postgres', 'postgres','333.333.333.333','5432')) --master

backend = function(txn)
res = assert (con:execute('select client_addr from pg_stat_replication order by replay_lag asc limit 1'))
row = res:fetch ({}, "a")
while row do
        ip = string.format("%-12s", row.client_addr)
        row = res:fetch (row, "a")
end
result = "backend1"
if ip == '111.111.111.111' then
result = "backend1"
elseif ip == '222.222.222.222' then
result = "backend2"
end
return result
end

core.register_fetches("choose_backend", backend)

Haproxy 必须从源代码编译,因为默认情况下 LUA 支持在其中被禁用。另外,你需要安装 luarocksluasql-postgres