Prefetch count -- Prefetch count, prefetchcount --
I. Preface
As mentioned above, if multiple consumers subscribe to messages in the same Queue at the same time, messages in the Queue will be evenly distributed to multiple consumers. At this time, if the processing time of each message is different, it may cause some consumers to stay busy, while others will soon finish their work and remain idle. We can set prefetchCount to limit the number of messages each Queue sends to each consumer. For example, if prefetchCount is set to 1, Queue sends a message each time to each consumer; after the consumer completes processing the message, the Queue will send a message to the consumer.
Ii. Examples
Production end:
#-*-Coding: UTF-8-*-import pikaconnection = pika. blockingConnection (pika. connectionParameters (host = 'localhost') channel = connection. channel () # declare the queue and make the queue persistent channel. queue_declare (queue = 'Task _ queue ', durable = True) # message = "Hello, World! "Channel. basic_publish (exchange = '', routing_key = 'Task _ queue ', body = message, properties = pika. basicProperties (delivery_mode = 2, # message persistence) print ('[x] Sent % R' % message) connection. close ()
Consumer:
#-*-Coding: UTF-8-*-import pikaimport timeimport randomconnection = pika. blockingConnection (pika. connectionParameters (host = 'localhost') channel = connection. channel () # declares a queue and the queue persists the channel. queue_declare (queue = 'Task _ queue ', durable = True) print (' [*] Waiting for messages. to exit press CTRL + C') def callback (ch, method, properties, body): print ('[x] Received % R' % body) time. sleep (random. randint (1, 20) print ('[x] done') # When the message processing is complete, actively notify rabbitmq, and then rabbitmq will delete # This message ch in the queue. basic_ack (delivery_tag = method. delivery_tag) # prefetch_count = 1 if a message in the consumer is not processed # the consumer will not send a new message channel to the consumer. basic_qos (prefetch_count = 1) channel. basic_consume (callback, queue = 'Task _ queue ') # accept it forever. If not, the channel will be stuck here. start_consuming ()
You can run multiple consumers to receive messages continuously. You can see that the next message is accepted only when the message processing in the consumer is complete.