openresty / lua-resty-balancer

A generic consistent hash implementation for OpenResty/Lua
322 stars 77 forks source link

nodes with"weight" does not work correctly? #11

Closed xiaoxuanzi closed 7 years ago

xiaoxuanzi commented 7 years ago

I try to follow it. Below is lua code in my nginx.conf:

` init_by_lua_block { local resty_chash = require "resty.chash"

    local server_list = {
        ["192.168.46.135:80"] = 3,
        ["192.168.46.136:80"] = 1,
    }

    local str_null = string.char(0)

    local servers, nodes = {}, {}
    for serv, weight in pairs(server_list) do
        local id = string.gsub(serv, ":", str_null)

        servers[id] = serv
        nodes[id] = weight
    end

    local chash_up = resty_chash:new(nodes)

    package.loaded.my_chash_up = chash_up
    package.loaded.my_servers = servers
}

upstream backend_lua {
    server 0.0.0.1;
    balancer_by_lua_block {
        local strutil = require "strutil"
        local to_str = strutil.to_str
        local b = require "ngx.balancer"

        local chash_up = package.loaded.my_chash_up
        local servers = package.loaded.my_servers

        local id = chash_up:find(ngx.var.arg_cid)
        local server = servers[id]
        ngx.log(ngx.ERR, to_str('id : ', id,' servers: ',servers,' server: ', server))
        assert(b.set_current_peer(server))
    }
}

    location /t {
        access_log  logs/access.log reqjson;
        proxy_pass http://backend_lua;
    }

` There are 2 nodes: 192.168.46.135:80 and 192.168.46.136:80. In the init block, the weight of node 192.168.46.135:80 is 3, and another is 1. And i use 100000 cid to test,
I expect that the request delivered to node 192.168.46.135:80 is 3 times that of B. However, the request delivered to node 192.168.46.135:80 is 71925.

DO YOU encounter the same problem? OR What wrong with me?

doujiang24 commented 7 years ago

@xiaoxuanzi Yeah, there won't be exactly 3 times. http://www.last.fm/user/RJ/journal/2007/04/10/rz_libketama_-_a_consistent_hashing_algo_for_memcache_clients