HAProxy中的自定义负载平衡

时间:2017-11-15 17:00:56

标签: load-balancing haproxy

我正在使用HAProxy来平衡我的HTTP请求。我想知道是否有任何方法可以根据每个服务器返回的响应自定义后端服务器的选择。我有一个servlet可以返回响应(连接到它的客户端数量)。我想使用此信息并将请求路由到编号最小的后端服务器。

我的HAProxy配置如下:

listen http_front xx.xx.xx.xx:8080
  mode http
  option httpchk GET /servlet/GetClientCountServlet
  server app1 xx.xx.xx.xx:8080 check port 8080
  server app2 xx.xx.xx.xx:8080 check port 8080
  server app3 xx.xx.xx.xx:8080 check port 8080

2 个答案:

答案 0 :(得分:0)

对于您的用例,并非最不平衡的模式工作吗?否则,我可以使用Lua脚本来自定义使用HAProxy

完成负载平衡的方式

答案 1 :(得分:0)

在我朝着同一个方向寻找解决方案时,这可能会有所帮助:

通过自定义lua脚本进行负载平衡

创建一个名为minimum_sessions.lua的文件,并添加以下代码:

local function backend_with_least_sessions(txn)
    -- Get the frontend that was used
    local fe_name = txn.f:fe_name()

    local least_sessions_backend = ""
    local least_sessions = 99999999999

    -- Loop through all the backends. You could change this
    -- so that the backend names are passed into the function too.
    for _, backend in pairs(core.backends) do


        -- Look at only backends that have names that start with
        -- the name of the frontend, e.g. "www_" prefix for "www" frontend.
        if backend and backend.name:sub(1, #fe_name + 1) == fe_name .. '_' then
            local total_sessions = 0

            -- Using the backend, loop through each of its servers
            for _, server in pairs(backend.servers) do

                -- Get server's stats
                local stats = server:get_stats()

                -- Get the backend's total number of current sessions
                if stats['status'] == 'UP' then
                    total_sessions = total_sessions + stats['scur']
                    core.Debug(backend.name .. ": " .. total_sessions)
                end
            end

            if least_sessions > total_sessions then
                least_sessions = total_sessions
                least_sessions_backend = backend.name
            end
        end
    end

    -- Return the name of the backend that has the fewest sessions
    core.Debug("Returning: " .. least_sessions_backend)
    return least_sessions_backend
end

core.register_fetches('leastsess_backend', backend_with_least_sessions)

此代码将循环访问所有以与当前前端相同的字母开头的后端,例如,为前端www查找后端www_dc1和www_dc2。然后它将找到当前会话最少的后端并返回其名称。

使用lua-load指令将文件加载到HAProxy中。然后,在您的前端添加一条use_backend行,以将流量路由到活动会话最少的后端。

global
    lua-load /path/to/least_sessions.lua

frontend www
    bind :80
    use_backend %[lua.leastsess_backend]

backend www_dc1
    balance roundrobin
    server server1 192.168.10.5:8080 check maxconn 30

backend www_dc2
    balance roundrobin
    server server1 192.168.11.5:8080 check maxconn 30

更多详细信息: https://www.haproxy.com/de/blog/5-ways-to-extend-haproxy-with-lua/