Skip to content

Instantly share code, notes, and snippets.

@kristaps
Created April 4, 2014 23:39
Show Gist options
  • Save kristaps/9985184 to your computer and use it in GitHub Desktop.
Save kristaps/9985184 to your computer and use it in GitHub Desktop.
# Example of multiple threads sharing an AMQP connection
import time
import threading
import random
import argparse
import rabbitpy
INSULTS = [
'imbecile',
'scoundrel',
'nincompoop',
'numbskull',
'nitwit',
'simpleton'
]
RABBITMQ_URL = 'amqp://guest:guest@localhost/%2F?locale=en_US.UTF-8'
arg_parser = argparse.ArgumentParser("Throw stuff over RabbitMQ")
arg_parser.add_argument('listen_queue', help='Queue to consume from')
arg_parser.add_argument('insult_queue', help='Queue the other client will consume from')
args = arg_parser.parse_args()
conn = rabbitpy.Connection(RABBITMQ_URL)
keep_insulting = True
def throw_insults():
chan = conn.channel()
while keep_insulting:
insult = random.choice(INSULTS) + '!'
rabbitpy.Message(chan, insult).publish('', args.insult_queue)
print "We said:", insult
time.sleep(0.1)
threads = []
for i in xrange(5):
t = threading.Thread(target=throw_insults)
t.setDaemon(True)
threads.append(t)
t.start()
chan = conn.channel()
queue = rabbitpy.Queue(chan, args.listen_queue)
queue.declare()
try:
for msg in queue.consume_messages(True):
print "They said:", msg.body
except KeyboardInterrupt:
print "Got KeyboardInterrupt"
keep_insulting = False
for t in threads:
t.join()
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment