Skip to content

Instantly share code, notes, and snippets.

@btel
Created January 6, 2020 17:15
Show Gist options
  • Save btel/59f50548d70d31128007d9a0b0db21ce to your computer and use it in GitHub Desktop.
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
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)
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