Bash 单侧平衡。如何在haproxy检查器中查找最小值?

Bash 单侧平衡。如何在haproxy检查器中查找最小值?,bash,psql,haproxy,Bash,Psql,Haproxy,我正在尝试配置Haproxy以平衡postgres副本。 主要任务:应该将请求重定向到具有最新数据的节点。 检查主节点上运行的数据相关性: select client_addr AS client, (pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn))::int / 1024 as total_lag from pg_stat_replication; 使用此命令,我将获得主机和复制延迟的列表。 例如: 111.111.111.111 | 15

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

select client_addr AS client, (pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn))::int / 1024 as total_lag from pg_stat_replication;
使用此命令,我将获得主机和复制延迟的列表。 例如:

111.111.111.111 | 152
222.222.222.222 | 9
333.333.333.333 | 4700
我需要一个最小值的主机。 我不明白三件事:

  • 如何将副本名称传递给自定义haproxy\u检查器
  • 如何比较这些值​​获得
  • 如何基于给定值指定haproxy​​将请求切换到哪个副本
  • 我应用了以下设置: 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
    
    选择backend.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支持。此外,您需要在haproxy 2.2版中安装luarocks和luasql postgres。在上面,Lua支持已经包括在内,从源代码安装它是没有意义的。