The path of Python 48-RABBITMQ

Source: Internet
Author: User
Tags uuid rabbitmq

Installing the Pika Module

Install under Linux

pip3.5 Install Pika


A simple example of Message Queuing

Send Side

Import pikaconnection = Pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = Connection.channel () # Declaration queue Queuechannel.queue_declare (queue= "test") # RABBITMQ message cannot be sent directly to the queue, it always needs to go through an exchange channel.basic_publish (exchange= "", routing_key= "test", body= "Hello world!") Print ("[x] sent ' Hello world! '") Connection.close ()

Receiving end

Import pikaconnection = Pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = Connection.channel () # declares queue queue,receive the reason for declaring a queue is not necessarily that the sending side starts first, If the receive side starts first declare the queue Channel.queue_declare (queue= "test") def callback (ch, method, properties, body): Print ("[x] Received%r "% body" channel.basic_consume (callback, queue= "test", no_ack=true) print ("[*] waiting for messages, to exit PR ESS Ctrl + C ") channel.start_consuming ()

In this way, RABBITMQ sends the message to the receiver in turn, similar to the load balancer


The above situation is the receiver does not respond, if there is no response, the receiver as long as the message from the queue, there is no such data in the queue, sometimes in order to avoid such a request, the receiver must receive a message and execute, you can let the receiver send a response, and then rabbitmq the message deleted

The sender does not change

Receiving end

Import Pikaimport timeconnection = Pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = Connection.channel () # declares queue queue,receive the reason for declaring a queue is not necessarily that the sending side starts first, If the receive side starts first declare the queue Channel.queue_declare (queue= "test") def callback (ch, method, properties, body): Print ("[x] Received%r "% body" time.sleep (+) Ch.basic_ack (delivery_tag=method.delivery_tag) # Channel.basic_consume (Callback, Queue= "Test", No_ack=true) Channel.basic_consume (callback, queue= "test") Print ("[*] waiting for messages, to exit press CTRL + C ") channel.start_consuming ()


RABBITMQ persistent, just modify the sending side to

Send Side

Import pikaconnection = pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = connection.channel () #  Declaration queue Queue# channel.queue _declare (queue= "test") Channel.queue_declare (queue= "test",  durable=true) # rabbitmq messages cannot be sent directly to the queue, It always needs to go through an exchange # channel.basic_publish (exchange= "",#                        routing_key= "Test",#                         body= "hello world!") Channel.basic_publish (exchange= "",                       routing_key= "Test",                       body= " hello world! ", &NBsp;                      properties=pika. Basicproperties (delivery_mode=2)) print ("[x] sent  ' hello world! '") Connection.close ()


Fair distribution

If rabbit in order to send the message to the individual consumers, regardless of consumer load, it is likely to occur, a machine is not high-profile consumers piled up a lot of message processing, while the high-profile consumers have been very easy. To solve this problem, you can configure perfetch=1 on each consumer side, meaning to tell rabbitmq not to send me any new messages until I have finished with the current consumer message.

This only needs to modify the receiving end

Import Pikaimport timeconnection = Pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = Connection.channel () # declares queue queue,receive the reason for declaring a queue is not necessarily that the sending side starts first, If the receive side starts first to declare the queue Channel.queue_declare (queue= "test") def callback (ch, method, properties, body): Print ("ch", CH) pr Int ("Method", method) print ("Properties", properties) Print ("[x] received%r"% body) time.sleep () ch.basic_ ACK (Delivery_tag=method.delivery_tag) Channel.basic_qos (prefetch_count=1) Channel.basic_consume (callback, queue= " Test ") Print (" [*] waiting for messages, to exit press CTRL + C ") channel.start_consuming ()


Message Publishing and Subscriptions

The previous examples are basically 1 to 1 messages sent and received, that is, the message can only be sent to the specified queue, but sometimes you want your message to be received by all the queue, similar to the effect of the broadcast, it is necessary to use Exchange

Exchange is defined with a type that determines exactly which queue matches the condition and can receive messages


Fanout: All bind to this Exchange queue can receive messages

Direct: The only queue that is determined by Routingkey and exchange can receive messages

Topic: All Routingkey that conform to Routingkey (which can be an expression at this time) can receive messages from the bind queue

Expression symbol Description: #代表一个或多个字符, * represents any character

Example: #.a will match A.A,AA.A,AAA.A, etc.

*.A will match A.A,B.A,C.A, etc.

Note: Using Routingkey for #,exchange type topic is equivalent to using fanout

Headers: Decide which queue to send messages to by headers


Fanout mode

Send Side

Import pikaconnection = Pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = Connection.channel () channel.exchange_declare (exchange= "test", type= " Fanout ") message =" Hello world! " Channel.basic_publish (exchange= "test", routing_key= "", body=message) print ("[X] S ENT%r "% message" connection.close ()

Receiving end

Import pikaconnection = Pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = Connection.channel () channel.exchange_declare (exchange= "test", type= " Fanout ") result = Channel.queue_declare (exclusive=true) queue_name = Result.method.queuechannel.queue_bind (exchange= "Test", Queue=queue_name) print ("[*] waiting for messages, to exit press CTRL + C") def callback (ch, method, properties, body) : Print ("[x] received%r"% body) Channel.basic_consume (callback, Queue=queue_name, No_ack=true) Channel.start_ Consuming ()


Direct mode

Send Side

Import pikaconnection = Pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = Connection.channel () channel.exchange_declare (exchange= "test", type= " Direct ") message =" Hello world! "                      Severity = "test123" Channel.basic_publish (exchange= "test", routing_key= "test123", body=message) Print ("[x] Sent%r:%r"% (severity, message)) Connection.close ()

Receiving end

Import pikaconnection = Pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = Connection.channel () channel.exchange_declare (exchange= "test", type= " Direct ") result = Channel.queue_declare (exclusive=true) queue_name = result.method.queueseverity =" Test123 " Channel.queue_bind (exchange= "test", Queue=queue_name, routing_key=severity) print ("[*] waiting for messages, to exit Press CTRL + C ") def callback (ch, method, properties, body): Print (" [x] received%r:%r "% (Method.routing_key, body)) Chann El.basic_consume (Callback, Queue=queue_name, No_ack=true) channel.start_consuming ()


Topic mode

Send Side

Import pikaconnection = Pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = Connection.channel () channel.exchange_declare (exchange= "test", type= " Topic ") message =" Hello world! "                      Routing_key = "Hello" Channel.basic_publish (exchange= "test", Routing_key=routing_key, body=message) Print ("[x] Sent%r:%r"% (routing_key, message)) Connection.close ()

Receiving end

Import pikaconnection = Pika. Blockingconnection (Pika. Connectionparameters ("127.0.0.1")) Channel = Connection.channel () channel.exchange_declare (exchange= "test", type= " Topic ") result = Channel.queue_declare (exclusive=true) queue_name = Result.method.queuerouting_key =" Hello " Channel.queue_bind (exchange= "test", Queue=queue_name, Routing_key=routing_key) print ("[*] waiting for messages, to Exit Press CTRL + C ") def callback (ch, method, properties, body): Print (" [x] received%r:%r "% (Method.routing_key, body)) Channel.basic_consume (Callback, Queue=queue_name, No_ack=true) channel.start_consuming ()


Rpc

Send Side

Import pikaimport uuid class fibonaccirpcclient (object):     def _ _init__ (self):         self.connection = pika. Blockingconnection (Pika. Connectionparameters (                 host= ' localhost ')          self.channel =  Self.connection.channel ()          result =  Self.channel.queue_declare (exclusive=true)         self.callback_queue  = result.method.queue         self.channel.basic_ Consume (self.on_response, no_ack=true,                                   &nbsP; queue=self.callback_queue)      def on_response (self, ch,  Method, props, body):         if self.corr_id ==  props.correlation_id:             Self.response = body     def call (self, n):         self.response = None         Self.corr_id = str (Uuid.uuid4 ())         self.channel.basic_ Publish (exchange= ',                                     routing_key= ' Rpc_queue ',                                    properties= Pika. Basicproperties (                                           reply_to = self.callback_queue,                                            correlation_id = self.corr_id,                                           ),                                     BODY=STR (n))          while self.response is None:             self.connection.process_data_events ()         return  Int (self.response)  fibonacci_rpc = fibonaccirpcclient ()  print (" [x] requesting  fib ("Response = fibonacci_rpc.call") print (" [.")  got %r " % response)

Receive side

Import pikaimport timeconnection = pika. Blockingconnection (Pika. Connectionparameters (        host= ' localhost '))  channel =  connection.channel ()  channel.queue_declare (queue= ' Rpc_queue ')  def fib (n):     if n == 0:        return 0     elif n == 1:        return 1     else:        return fib (n-1)  + fib ( n-2)  def on_request (ch, method, props, body):    n =  Int (body)      print (" [.")  fib (%s) " % n)     response = fib (n)       Ch.basic_publish (exchange= ",                      routing_key=props.reply_to,                      properties= Pika. Basicproperties (correlation_id =                                                             PROPS.CORRELATION_ID),                      body=str (response))     ch.basic_ack (Delivery_tag = method.delivery_tag)  channel.basic_qos ( prefetch_count=1) Channel.basic_consume (on_request, queue= ' Rpc_queue ')  print (" [x] Awaiting  rpc  requests ") channel.start_consuming () 


This article is from the "Eight Miles" blog, so be sure to keep this source http://5921271.blog.51cto.com/5911271/1912393

The path of Python 48-RABBITMQ

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.