Encapsulates a task into a message and sends it to a queue. Consumer will remove the task and execute the task.
Here we simplify the operation, send the message to the queue, consumer out the message calculation inside '. ' A few seconds to sleep.
task.py
#!/usr/bin/env pythonImportPikaImportsysconnection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost')) Channel=Connection.channel () channel.queue_declare (Queue='Task_queue', durable=True) Message=' '. Join (sys.argv[1:])or "Hello world!"channel.basic_publish (Exchange="', Routing_key='Task_queue', Body=Message, Properties=Pika. Basicproperties (Delivery_mode= 2,#Make message Persistent ))Print("[x] Sent%r"%message) Connection.close ()
work.py
#!/usr/bin/env pythonImportPikaImporttimeconnection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost')) Channel=Connection.channel () channel.queue_declare (Queue='Task_queue', durable=True)Print('[*] waiting for messages. To exit Press CTRL + C')defCallback (ch, method, properties, body):Print("[x] Received%r"%body) Time.sleep (Body.count (b'.')) Print("[x] done") Ch.basic_ack (Delivery_tag=method.delivery_tag) Channel.basic_qos (Prefetch_count=1) Channel.basic_consume (callback, queue='Task_queue') channel.start_consuming ()
Code explanation
Channel.queue_declare (queue='task_queue', durable=True) tells Rabbitmq never to lose the queue, Even if the RABBITMQ server is hung out.
defCallback (ch, method, properties, body):Print "[x] Received%r"%(body,) Time.sleep (Body.count ('.') ) Print "[x] done"Ch.basic_ack (Delivery_tag=Method.delivery_tag) Channel.basic_consume (callback, queue='Hello'in the previous example, if consumer suddenly dies, it loses the information that is being processed. How to avoid it? If consumer dies, how will this message be sent to other consumer? is to use the above code
Channel.basic_qos (prefetch_count=1 not
In other words, Don't dispatch a new message to a worker until it has processed and acknowledged the Previous one.
Until the end of the consumption of the news to send a new message to consumer, if not consumed, the message sent to another consumer.
Rabbitmq--work Queues (ii)