Python透過Pika發送與接收RabbitMQ上的訊息

安裝Pika

pip install pika

發送訊息

credentials = pika.PlainCredentials('user1', 'user1pw')
parameters = pika.ConnectionParameters(domain name or ip address,
                                       5672,
                                       '/',
                                       credentials)

connection = pika.BlockingConnection(parameters)
channel = connection.channel()

#指定channel名稱
channel.queue_declare(queue=queuechannel)

channel.basic_publish(exchange = '',
                      routing_key = queuechannel,
                      body = msg)
print(" [x] Sent 'Hello World!'")

connection.close()

接收訊息

basic_message_receiver.consume_messages(queueChannel)
def consume_messages(self, queue):

    def callback(channel, method, properties, body):
        print(' [x] Received %r' % body)

    self.channel.basic_consume(queue=queue, on_message_callback=callback, auto_ack=True)

    print(' [*] Waiting for messages. To exit press CTRL+C')
    self.channel.start_consuming()