RABBITMQ Combat (i)---------using the Pika Library to implement Hello World2016-05-18 23:29 This site (267) Pika is the official Python AMQP library written by the RABBITMQ team. Need to install PIKA:PIP3 installed Pika with more detailed comments, it is no longer elaborate
Producer Code:hello_world_producer.py:
ImportPika,sys#connect to the Rabbitmq,use the default vhostcredentials = Pika. Plaincredentials ("Guest","Guest") Conn_params = Pika. Connectionparameters ("localhost", credentials=credentials) Conn_broker = Pika. Blockingconnection (conn_params) #get a channel used to communicate with the Rabbitmqchannel = Conn_broker.channel () # Declare a exchangechannel.exchange_declare (exchange=' Hello-exchange ', type=' Direct ', passive=False, #if the exchange already existes,report a error. It means we want to declare an exchange. durable=True, #durable the message auto_delete=False#if the last consumer was over,do not delete the exchange auto#create a messagemsg = Sys.argv[1]msg_props = Pika. Basicproperties () Msg_props.content_type ="Text/plain"#publish the Messagechannel.basic_publish (body=msg, exchange=' Hello-exchange ', Properties=msg_props, routing_key=' Hola ')
Consumer Code
hello_world_consumer.py:
ImportPika#connect to the Rabbitmq,use the default vhostcredentials = Pika. Plaincredentials ("Guest","Guest") Conn_params = Pika. Connectionparameters ("localhost", credentials=credentials) Conn_broker = Pika. Blockingconnection (conn_params) #get a channel used to communicate with the Rabbitmqchannel = Conn_broker.channel () # Declare a exchangechannel.exchange_declare (exchange=' Hello-exchange ', type=' Direct ', passive=False, #if the exchange already existes,report a error. It means we want to declare an exchange. durable=True, #durable the message auto_delete=False) #if the last consumer was over,do not delete the Exchange auto#declare a queuechannel.queue_declare (queue="Hello-queue") #bind queue to an exchangechannel.queue_bind (queue=' Hello-queue ', exchange=' Hello-exchange ', routing_key=' Hola ') #define The consumer method to consumer message from a queuedefMsg_consumer (channel,method,header,body): Channel.basic_ack (Delivery_tag=method.delivery_tag)ifBody.decode ("ASCII") =="Quit": Channel.basic_cancel (consumer_tag=' Hello-consumer ') channel.stop_consuming ()Else: Print (body)return#subscribe Messagechannel.basic_consume (Msg_consumer, queue=' Hello-queue ', consumer_tag=' Hello-consumer ') #begin Loop until a quit message is sentchannel.start_consuming ()
To run the code:
You need to run consumer first, because we create queues in the consumer, and if you produce a message first, the message is discarded because there is no queue to route to.
$ python hello_world_consumer.pyb ' good ' B ' Hello World '
$ python hello_world_producer.py "good" $ python hello_world_producer.py "Hello World" $ python hello_world_producer.py " Quit
RABBITMQ Combat (i)---------using the Pika Library to implement Hello World