Skip to content

Instantly share code, notes, and snippets.

@CandyMi
Last active May 12, 2022 08:44
Show Gist options
  • Save CandyMi/29601db02334043f03fca8c38a7ee35a to your computer and use it in GitHub Desktop.
Save CandyMi/29601db02334043f03fca8c38a7ee35a to your computer and use it in GitHub Desktop.

最小连接数算法

Lua 实现

local toint = math.tointeger

local tsort = table.sort

local class = require "class"

local LoadBalance = class ("LoadBalance")

function LoadBalance:ctor()
  self.map = {}
  self.list = {}
  self.started = false
end

local function cmp(o1, o2)
  return o1.n < o2.n
end

function LoadBalance:sort()
  return tsort(self.list, cmp)
end

---comment 注册
---@param id string | integer  @唯一标识
---@param n integer ?          @初始连接数
function LoadBalance:set(id, n)
  if self.map[id] then
    error("LoadBalance already have this id.", 2)
  end
  local info = { n = toint(n) or 0, id = id }
  self.map[id] = info
  self.list[#self.list+1] = info
end

---comment 获取下一个`ID`
function LoadBalance:nextid()
  if not self.started then
    self.mask = #self.list
    if self.mask < 1 then
      error("LoadBalance is empty list.", 2)
    end
    self:sort()
    self.started = true
  end
  return self.list[1].id
end

---comment 递增连接数
---@param id   string | integer  @唯一标识
---@param step integer ?         @步长
function LoadBalance:incr(id, step)
  local info = self.map[id]
  if not info then
    error("LoadBalance can't find id.", 2)
  end
  info.n = info.n + (toint(step) or 1)
  self:sort()
end

---comment 递减连接数
---@param id   string | integer  @唯一标识
---@param step integer ?         @步长
function LoadBalance:decr(id, step)
  local info = self.map[id]
  if not info then
    error("LoadBalance can't find id.", 2)
  end
  info.n = info.n - (toint(step) or 1)
  self:sort()
end

使用示例

local lb = LoadBalance()

lb:set(1, 100)
lb:set(2, 102)

local id = lb:nextid(); lb:incr(id)
print(id)
local id = lb:nextid(); lb:incr(id)
print(id)
local id = lb:nextid(); lb:incr(id)
print(id)
local id = lb:nextid(); lb:incr(id)
print(id)
local id = lb:nextid(); lb:incr(id)
print(id)
local id = lb:nextid(); lb:incr(id)
print(id)

输出:

1
1
1
2
2
1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment