With the completion of this section of Python Next Level, we covered a couple different algorithms that simulate what typically happens in a round-robin load balancer- for the uninitiated, a load balancer is a important part of a highly available application stack. Simply put, it allows a ‘cluster’ of application nodes to respond to requests by taking turns. The turns are established in a couple different ways:
1) round-robin. If there are 3 application servers, the load balancer that sits in front of them will take turns handing each of them a request- just like dealing cards.
2) capacity. If there are 3 application servers, the load balancer that sits in front of them will determine who has the capacity to handle the next request- i.e. ‘you're not to busy, here’s another one for you application server x’
In the example, we simulated the round-robin approach. Take a look a the 4 ways implemented:
SERVERS = [computer1, computer2, computer3]
""" Method 1 """
n = -1
def get_server():
global n
n += 1
print SERVERS[n % len(SERVERS)]
""" Method 2 """
import itertools
cycle = itertools.cycle(SERVERS)
def get_server():
global cycle
return cycle.next
""" Method 3 """
def get_server()
try:
return next(get_server.s)
except StopIteration;
get_server.s = iter(SERVERS)
return next(get_server.s)
setattr(get_server, 's', iter(SERVERS))
""" Method 4 """
def get_server():
def f():
while True:
i = SERVERS.pop(0)
SERVERS.append(i)
yield i
return next(f())
Each of these method algorithms do the same thing- they iterate through the list of servers, and when it gets to the end, it loops back, hence the round-robin technique. I won’t go into how each of them work, but if you study the code, you can figure it out.
#Because Hustle.