bash - 代理平衡。如何在 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
我需要一个具有最小值的主机。我不明白三件事:
- 如何将副本名称传递给自定义 haproxy_checker?
- 如何比较获得的值?
- 如何根据给定的值指定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
选择后端.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 支持。此外,您需要安装luarocks和luasql-postgres
推荐阅读
- json - .Net Core 2.1 ModelBinding 在发布 JSON 时不起作用
- microsoft-cognitive - 如何获取 Azure 认知语音服务的凭据
- c - C - 可以添加邻居的图节点(无向)
- firebase - 错误:无法获取 Firebase 项目项目名称。请确保该项目存在并且您的帐户有权访问它
- eclipse - 自动代码完成不适用于 Eclipse
- python - 在更多线程中使用 Python gRPC 客户端存根时可以提高性能吗?
- python - 如何在 Pandas 中替换 Panel 并将其导出到 excel
- delphi - Delphi 最快的 FileSize 大小 > 10gb
- python - 尝试使用 shutil.move 移动文件时出现 WinError 32 和 Errno 13
- angular - 可观察到的“完成”后退订