---restore content starts---
Python rabbitmq queue usage about Python introduction
On the Python queue, there are two built-in, one is the thread queue, the other is the process queue, but both of the queue can only be in the same process between the threads or between the parent process and the child process communication, and can not be between the program and program information Exchange, At this point we need a middleware to implement communication between programs.
RabbitMQ
MQ is not a Python built-in module, but a need for you to install additional (Ubunto can be directly apt-get the rest please Baidu yourself. ) program, you can call MQ to send or receive queue requests through the built-in pika module in Python. Next we'll look at several python-called MQ patterns (the author customizes the pattern names of Chinese images) and methods.
RABBITMQ Setting the remote link account password
To start the RABBITMQ Web service:
2. Remote Access RABBITMQ: Add a user yourself with the following steps:
L1. Create an Admin User: sudo rabbitmqctl add_user admin 123123
L2. Set the user to Administrator role: sudo rabbitmqctl set_user_tags admin Administrator
L3. Set permissions: sudo rabbitmqctl set_permissions -P '/' admin '. ' ‘.‘ ‘.‘
L4. Restart RABBITMQ services: sudo service rabbitmq-server restart
After that, you can connect RABBITMQ server remotely with the Admin user.
Polling consumption mode
In this mode, the party sending the queue sends the message to the specified queue in MQ, and if there is a consumer in the appropriate queue, the message is obtained and the messages in the queue are consumed.
If multiple consumers are connected to the queue at the same time, the messages in the queue will be consumed in a polling manner.
Next is the code example:
Producer Producers
#!/usr/bin/env pythonImportpikacredentials= Pika. Plaincredentials ('Admin','123456') Connection=Pika. Blockingconnection (Pika. Connectionparameters ('192.168.56.19', 5672,'/', credentials)) Channel=Connection.channel ()#declaring a queueChannel.queue_declare (queue='Balance')#n RabbitMQ A message can never is sent directly to the queue, it always needs to go through an exchange.Channel.basic_publish (exchange="', Routing_key='Balance', Body='Hello world!')Print("[x] Sent ' Hello world! '") Connection.close ()
Queue status can be viewed in the MQ server after the queue has been sent
[Email protected] ~]# rabbitmqctl list_queueslisting queues ... hello 1
Consumer Consumer
#_*_coding:utf-8_*___author__='Alex Li'Importpikacredentials= Pika. Plaincredentials ('Admin','123456') Connection=Pika. Blockingconnection (Pika. Connectionparameters ('192.168.56.19', 5672,'/', credentials)) Channel=Connection.channel ()#May ask why we declare the queue again? We had already declared it in our previous code.#we could avoid so if We were sure that the queue already exists. For example if send.py program#was run before. But we ' re not yet sure which program to run first. In such cases it ' s a good#practice to repeat declaring the queue in both programs.Channel.queue_declare (queue='Balance')defCallback (ch, method, properties, body):Print("[x] Received%r"%body) Channel.basic_consume (callback, queue='Balance', No_ack=True)Print('[*] waiting for messages. To exit Press CTRL + C') channel.start_consuming ()
After receiving the queue, look at the status of the queue
[Email protected] ~]# rabbitmqctl list_queueslisting queues ... hello 0
Queue Persistence
When RABBITMQ unexpectedly goes down, there may be a need to persist the queue (messages in the queue do not disappear).
Producer
# cheng#!/usr/bin/EnvPythonimport pikacredentials= Pika. Plaincredentials ('Admin','123456') Connection=Pika. Blockingconnection (Pika. Connectionparameters ('192.168.56.19',5672,'/', credentials)) Channel=Connection.channel () # Declaration Queuechannel.queue_declare (Queue='Durable', durable=True) # N RabbitMQ a message can never is sent directly to the queue, it always needs to go through an exchange.channel . Basic_publish (Exchange="', Routing_key='Durable', Body='Hello cheng!', Properties=Pika. Basicproperties (Delivery_mode=2, # Makemessage persistent)) Print ("[x] Sent ' Hello cheng! '") Connection.close ()
Check queue after execution, note the queue name and the number of messages contained in the queue
[Email protected] ~]# rabbitmqctl list_queueslisting queues ... durable 1
#重启rabbitmq
~]# systemctl Restart rabbitmq-Server
~]# rabbitmqctl list_queueslisting queues ... durable #队列以及消息并未消失
Execute Consumer Code
Cunsumer
# cheng# _*_coding:utf-8_*___author__='Alex Li'Import Pikacredentials= Pika. Plaincredentials ('Admin','123456') Connection=Pika. Blockingconnection (Pika. Connectionparameters ('192.168.56.19',5672,'/', credentials)) Channel=Connection.channel () # What do we declare the queue again? We have already declared itinchOur previous code.# We could avoidifWe were sure that the queue already exists. For exampleifsend.py program# was run before. But we're not yet sure which program to run first. In such cases it's A good# practice to repeat declaring the queueinchboth Programs.channel.queue_declare (queue='Durable', durable=True) def callback (ch, method, properties, body): Print ("[x] Received%r"%body) ch.basic_ack (Delivery_tag=Method.delivery_tag) Channel.basic_consume (callback, queue='Durable', #no_ack=True) Print ('[*] waiting for messages. To exit Press CTRL + C') channel.start_consuming ()
The information can be received correctly.
View the queue again.
[Email protected] ~]# rabbitmqctl list_queueslisting queues ... durable 0
Broadcast mode
When producer sends a message to the queue, all consumer receive the message, and it is important to note that the relationship between producer and concerned in this mode is similar to that of radio and radio, and if the radio is not received after the broadcast, the message will be lost.
It is recommended to perform concerned first
Concerned
# _*_coding:utf-8_*___author__='Alex Li'Import Pikacredentials= Pika. Plaincredentials ('Admin','123456') Connection=Pika. Blockingconnection (Pika. Connectionparameters ('192.168.56.19',5672,'/', credentials)) Channel=Connection.channel () channel.exchange_declare (Exchange='Clogs', type='fanout') Result= Channel.queue_declare (exclusive=true) # does not specify a queue name, rabbit randomly assigns a name, exclusive=True will automatically delete the queue after the consumer using this queue disconnects queue_name=Result.method.queuechannel.queue_bind (Exchange='Clogs', Queue=queue_name) Print ('[*] waiting for logs. To exit Press CTRL + C') def callback (ch, method, properties, body): Print ("[x]%r"%body) Channel.basic_consume (callback, queue=queue_name, No_ack=True) channel.start_consuming ()
Producer
Import Pikaimport syscredentials= Pika. Plaincredentials ('Admin','123456') Connection=Pika. Blockingconnection (Pika. Connectionparameters ('192.168.56.19',5672,'/', credentials)) Channel=Connection.channel () channel.exchange_declare (Exchange='Clogs', type='fanout') Message=' '.Join(sys.argv[1:]) or"Info:hello world!"channel.basic_publish (Exchange='Clogs', Routing_key="', Body=message) Print ("[x] Sent%r"%message) Connection.close ()
The first few ways to use RABBITMQ are introduced here, and the next blog introduces advanced usage.
Python rabbitmq Queue Usage (introductory article)