Skip to content

Instantly share code, notes, and snippets.

@swinton
Created April 22, 2013 20:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swinton/5438483 to your computer and use it in GitHub Desktop.
Save swinton/5438483 to your computer and use it in GitHub Desktop.
RabbitMQ basic.cancel example with Pika. See: http://www.rabbitmq.com/amqp-0-9-1-quickref.html#basic.cancel
#!/usr/bin/env python
import sys
import time
import uuid
from functools import partial
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_tasks',
exchange_type='direct')
result = channel.queue_declare(queue='task')
queue_name = result.method.queue
channel.queue_bind(exchange='direct_tasks',
queue=queue_name,
routing_key='task')
def callback(ct, ch, method, properties, body):
print " [x] Received %r" % (body,)
ch.basic_ack(delivery_tag=method.delivery_tag)
ch.basic_cancel(consumer_tag=ct, nowait=False)
print " [x] Done"
channel.basic_qos(prefetch_count=1)
try:
while True:
print ' [*] Waiting for tasks. To exit press CTRL+C'
consumer_tag = uuid.uuid1().hex
channel.basic_consume(partial(callback, consumer_tag),
queue=queue_name,
consumer_tag=consumer_tag)
channel.start_consuming()
print " [x] Sleeping..."
time.sleep(5)
except KeyboardInterrupt:
sys.exit(0)
#!/usr/bin/env python
import sys
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_tasks',
exchange_type='direct')
channel.queue_declare(queue='task')
message = ' '.join(sys.argv[1:]) or 'Hello World!'
channel.basic_publish(exchange='direct_tasks',
routing_key='task',
body=message,
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
))
print " [x] Sent %r" % (message)
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment