RABBITMQ requires Erlang and Pika
1.RabbitMQ and Erlang versions must match, otherwise no process error is reported
2.RabbitMQ Erlang.cookie and Windows Erlang.cookie must be the same
In Windows installation RABBITMQ need to configure environment variables, one is Erlang environment variable, one is RABBITMQ environment variable remember!
Send side: Producer
| 12345678910111213141516 |
importpikaconnection =pika.BlockingConnection( pika.ConnectionParameters(‘localhost‘))channel =connection.channel()#声明一个管道,在管道里发消息#声明queuechannel.queue_declare(queue=‘hello‘)#在管道里还得声明一个队列channel.basic_publish(exchange=‘‘, routing_key=‘hello‘,#就是列队queue名字 body=‘Hello World‘#消息内容 )print(" [x] Sent ‘Hello World!‘")connection.close()#不用关闭管道,关闭连接就行 |
Receiving End: Consumer
| 12345678910111213141516171819202122232425262728293031323334353637 |
importpika# 建立到达RabbitMQ Server的connection# 此处RabbitMQ Server位于本机-localhostconnection =pika.BlockingConnection(pika.ConnectionParameters( ‘localhost‘))channel =connection.channel()# 声明queue,确认要从中接收message的queue# queue_declare函数是幂等的,可运行多次,但只会创建一次# 若可以确信queue是已存在的,则此处可省略该声明,如producer已经生成了该queue# 但在producer和consumer中重复声明queue是一个好的习惯channel.queue_declare(queue=‘hello‘)print(‘ [*] Waiting for messages. To exit press CTRL+C‘)# 定义回调函数# 一旦从queue中接收到一个message回调函数将被调用# ch:channel# method:# properties:# body:messagedefcallback(ch, method, properties, body): print(" [x] Received %r"%body)# 从queue接收message的参数设置# 包括从哪个queue接收message,用于处理message的callback,是否要确认message# 默认情况下是要对消息进行确认的,以防止消息丢失。# 此处将no_ack明确指明为True,不对消息进行确认。channel.basic_consume(callback, queue="hello", no_ack=True)# 开始循环从queue中接收message并使用callback进行处理channel.start_consuming() |
PYTHON-RABBITMQ (Simple send model)