Talking RabbitMQ with Python and

2019-05-14  本文已影响0人  芒果菠萝蛋炒饭

什么是 RabbitMQ

编码时间

使用Python3和Kombu来建立一个生产者

from kombu import Connection, Exchange 

exchange = Exchange("example-exchange", type="direct")
from kombu import Connection, Exchange, Producer
producer = Producer(exchange=exchange, channel=channel, routing_key="BOB")
from kombu import Connection, Exchange, Producer, Queue

queuer = Queue(name="example-queue", exchange=exchange, routing_key="BOB")
queue.maybe_bind(conn)
queue.declare()
producer.publish("Hello there!")

一个完整的生产者就创建完成了,完整代码如下:

from kombu import Connection, Exchange, Producer, Queue
rabbit_url = “amqp://localhost:5672/”
conn = Connection(rabbit_url)
channel = conn.channel()
exchange = Exchange(“example-exchange”, type=”direct”)
producer = Producer(exchange=exchange, channel=channel, routing_key=”BOB”)
queue = Queue(name=”example-queue”, exchange=exchange, routing_key=”BOB”)
queue.maybe_bind(conn)
queue.declare()
producer.publish(“Hello there!”)
rabbitmqctl list_queues
Listing queues …
example-queue 1

创建消费者

from kombu import Connection, Exchange, Queue, Consumer
rabbit_url = “amqp://localhost:5672/”
conn = Connection(rabbit_url)
exchange = Exchange(“example-exchange”, type=”direct”)
queue = Queue(name=”example-queue”, exchange=exchange, routing_key=”BOB”)
def process_message(body, message):
    print(“The body is {}”.format(body))
    message.ack()
with Consumer(conn, queues=queue, callbacks=[process_message], accept=[“text/plain”]):
conn.drain_events(timeout=2)
from kombu import Connection, Exchange, Queue, Consumer
rabbit_url = “amqp://localhost:5672/”
conn = Connection(rabbit_url)
exchange = Exchange(“example-exchange”, type=”direct”)
queue = Queue(name=”example-queue”, exchange=exchange, routing_key=”BOB”)
def process_message(body, message):
  print(“The body is {}”.format(body))
  message.ack()
with Consumer(conn, queues=queue, callbacks=[process_message], accept=["text/plain"]):  
  conn.drain_events(timeout=2)
The body is Hello there!

现在你可以使用rabbitmqctl来检测队列是否为空了。

上一篇下一篇

猜你喜欢

热点阅读