Skip to content

Instantly share code, notes, and snippets.

@zhanglintc
Created September 5, 2020 13:13
Show Gist options
  • Save zhanglintc/be0923b144d36e47fa82a03fe86c048c to your computer and use it in GitHub Desktop.
Save zhanglintc/be0923b144d36e47fa82a03fe86c048c to your computer and use it in GitHub Desktop.
load balance method
def make_balance_list(servers):
whole_weight = sum(srv[1] for srv in servers)
balance = []
weight_so_far = 0
for server in servers:
weight = server[1]
weight_so_far += weight
balance.append(weight_so_far / whole_weight)
return balance
def choose_server(servers, balance):
import random
import bisect
idx = bisect.bisect(balance, random.random())
return servers[idx][0]
if __name__ == '__main__':
# test
servers = [
('192.168.0.101', 1),
('192.168.0.102', 2),
]
balance = make_balance_list(servers)
res = [choose_server(servers, balance) for _ in range(10000)]
import collections
counter = collections.Counter(res)
print(counter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment