首页 > 解决方案 > 代理平衡。如何在 haproxy 检查器中找到最小值?

问题描述

我正在尝试配置 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切换请求?

标签: bashpsqlhaproxy

解决方案


我应用了这些设置: 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

选择后端.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


推荐阅读