Created
January 6, 2020 17:15
-
-
Save btel/59f50548d70d31128007d9a0b0db21ce to your computer and use it in GitHub Desktop.
simple load balancer with zeromq. Adapted from http://zguide.zeromq.org/py:all#ROUTER-Broker-and-DEALER-Workers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import zmq | |
import random | |
import time | |
raw_input = input | |
context = zmq.Context() | |
# Socket to send messages on | |
sender = context.socket(zmq.ROUTER) | |
sender.bind("tcp://*:5557") | |
print("Press Enter when the workers are ready: ") | |
_ = raw_input() | |
print("Sending tasks to workers…") | |
# Initialize random number generator | |
random.seed() | |
# Send 100 tasks | |
total_msec = 0 | |
for task_nbr in range(100): | |
address, _, _ = sender.recv_multipart() | |
# Random workload from 1 to 100 msecs | |
workload = random.randint(1, 100) | |
total_msec += workload | |
sender.send_multipart([address, b'', ('%i' % workload).encode('ascii')]) | |
print("Total expected cost: %s msec" % total_msec) | |
# Give 0MQ time to deliver | |
time.sleep(1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import time | |
import zmq | |
context = zmq.Context() | |
# Socket to receive messages on | |
receiver = context.socket(zmq.REQ) | |
receiver.connect("tcp://localhost:5557") | |
# Process tasks forever | |
while True: | |
receiver.send(b'ready') | |
s = receiver.recv() | |
# Simple progress indicator for the viewer | |
sys.stdout.write('.') | |
sys.stdout.flush() | |
# Do the work | |
time.sleep(int(s)*0.001) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment