RabbitMQ
MQ is all called the message queue, and Message Queuing (MQ) is an application-to-application communication method. Applications communicate by reading and writing messages to and from the queue (data for the application), without requiring a dedicated connection to link them. Message passing refers to the process of communicating between programs by sending data in a message, rather than by directly invoking each other, and directly invoking techniques such as remote procedure calls. Queuing refers to an application communicating through a queue. The use of queues removes the requirement that both the receiving and sending applications execute concurrently.
MQ Features
MQ is a typical representative of the consumer-producer model, where one end writes messages to the message queue, while the other end reads or subscribes to messages in the queue. MQ is similar to JMS, but the difference is that JMS is a standard and API definition for the Sun Java Messaging Middleware Service, and MQ follows the specific implementations and products of the AMQP protocol.
Send and Receive
Send
#!/usr/bin/env python#-*-coding:utf-8-*-#Author:jerry ShiImportpikaconnection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost')) Channel=Connection.channel () channel.queue_declare (Queue='Hello') channel.basic_publish (Exchange="', Routing_key='Hello', Body='Hello world!')Print("Hello world! has been sent") Connection.close ()
Receive
#!/usr/bin/env python#-*-coding:utf-8-*-#Author:jerry ShiImportpikaconnection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost')) Channel=Connection.channel () channel.queue_declare (Queue='Hello')Print'[*] waiting for messages. To exit Press CTRL + C'defCallback (ch, method, properties, body):Print("have received%r"%body) Channel.basic_consume (callback, queue='Hello', No_ack=True) channel.start_consuming ()
Message Distribution Polling Instances
Send
#!/usr/bin/env python#-*-coding:utf-8-*-#Author:jerry ShiImportpikaconnection=Pika. Blockingconnection (Pika. Connectionparameters ('localhost'))##相当建立一个socketChannel = Connection.channel ()##声明一个管道Channel.queue_declare (Queue='Hello')#declaring a queuechannel.basic_publish (Exchange="', Routing_key='Hello',#send a queue namebody='Hello world!')#What to sendPrint("sent ' Hello world! '")#Print the message when the send is completeConnection.close ()
Receive
#!/usr/bin/env python#-*-coding:utf-8-*-#Author:jerry ShiImportpikaconnection=Pika. Blockingconnection (Pika. Connectionparameters ('localhost')) Channel=Connection.channel () channel.queue_declare (Queue='Hello')#declare which queue to receive messages fromdefCallback (ch, method, properties, body):Print(" -", ch, method, properties)Print("[x] Received%r"%body)#Start Consumer NewsChannel.basic_consume (Callback,#call the callback function to process the message if you receive a messageQueue='Hello', No_ack=True)Print('[*] waiting for messages. To exit Press CTRL + C') channel.start_consuming ()#waiting to receive messages after running
RabbitMQ RPC
Rpc_client:
#!/usr/bin/env python#-*-coding:utf-8-*-#Author:jerry ShiImportPika,uuid,timeclassrpcclient (object):def __init__(self): self.connection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost'))#Establish a remote connectionSelf.channel= Self.connection.channel ()#establishing a declaration tunnelresult= Self.channel.queue_declare (exclusive=true)#generate a random queueSelf.callback_queue = Result.method.queue#Random QueueSelf.channel.basic_consume (Self.on_response,#call Op_response whenever you receive a messageno_ack=True, Queue=self.callback_queue)#statement to receive Callback_queue defon_response (self, ch, method, props, body):ifself.corr_id = = props.correlation_id:#determine if it was the last data I sent outSelf.response = Body#body is the return of the queue defCall (self, N): Self.response= None#Start setting response to Noneself.corr_id = str (UUID.UUID4 ())#generate a random stringSelf.channel.basic_publish (exchange="', Routing_key='Rpc_queue',#send a message to Rpc_queue.Properties=pika. Basicproperties (#message Persistence Pika. BasicpropertiesReply_to=self.callback_queue,#after generating the random queue sent to me, I told the server to return the message sent by this queueCORRELATION_ID=SELF.CORR_ID,#send UUID string to server), Body=STR (n))#information must be a string whileSelf.response isNone:#Respnse If it's empty, execute this loop .Self.connection.process_data_events ()#non-blocking version of Start_consuming (), there is a message returned, no message is returned. Print("") Time.sleep (0.5) returnint (self.response) RPC= Rpcclient ()#instantiation ofPrint("What you want to do is:") Response= Rpc.call (6)#call method, pass a parameterPrint("your result is:%r"% response)
Rpc_server:
#!/usr/bin/env python#-*-coding:utf-8-*-#Author:jerry ShiImportpika,timeconnection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost')) Channel=Connection.channel () channel.queue_declare (Queue='Rpc_queue')#Declare a rpe_queuedeffib (n):ifn = =0:return0elifn = = 1: return1Else: returnFIB (n-1) + fib (n-2)defon_request (ch, method, props, body): N= Int (body)#Receive Information Print("[.] Fib (%s)"%N) Response=fib (n) ch.basic_publish (Exchange="', Routing_key=props.reply_to,#the random queue that the client randomly generatesProperties=pika. Basicproperties (correlation_id=props.correlation_id),#after receiving the client-generated UUID, it regenerates itself into a UUID and returns it to the clientBODY=STR (response))#send a message to the clientCh.basic_ack (Delivery_tag=method.delivery_tag)#confirm that the message was consumedChannel.basic_qos (Prefetch_count=1) Channel.basic_consume (on_request, queue='Rpc_queue')Print("[x] awaiting RPC requests") channel.start_consuming ()
The rabbitmq of Python