Python Operations RABBITMQ server implements Message Queuing routing

Source: Internet
Author: User
RABBITMQ is a Message Queuing server, where we look at the server-side environment of PYTHON+PIKA+RABBITMQ to see how to use the Python operation RABBITMQ Server to implement Message Queuing routing capabilities

Python uses the Pika library (install: sudo pip install pika) to operate the RABBITMQ Message Queuing server (install: sudo apt-get install rabbitmq-server), Here we look at MQ-related routing capabilities.

Implementation of routing Keys

For example, there is a scene that needs to send messages to all the receivers, but if it needs to be freely customized, some messages are sent to some of the receivers, and some messages are sent to the other receivers. In this case, the routing key is used.

How the routing key works: Each receiving end of the message queue when binding the switch, you can set the corresponding routing key. When the sender sends information through the switch, it can indicate the routing key, and the switch sends the message to the corresponding message queue according to the routing key, so that the receiving end can receive the message.

This is followed by an article, or with send.py and receive.py to simulate the implementation of the function of the routing key. The send.py represents the sending side, and the receive.py represents the receiving end. The function of an instance is to send info, warning, error three levels of information to different receive ends.

send.py Code Analysis

#!/usr/bin/env python#coding=utf8import Pika connection = Pika. Blockingconnection (Pika. Connectionparameters (        ' localhost ')) channel = Connection.channel () #定义交换机, set type Directchannel.exchange_declare ( Exchange= ' Messages ', type= ' direct ') #定义三个路由键routings = [' info ', ' warning ', ' error '] #将消息依次发送到交换机 and set the routing key for routing in Routings:  message = '%s ' message. '% routing  channel.basic_publish (exchange= ' messages ',             routing_key= Routing,             body=message)  print Message connection.close ()

receive.py Code Analysis

#!/usr/bin/env python#coding=utf8import pika, sys connection = Pika. Blockingconnection (Pika. Connectionparameters (        ' localhost ')) channel = Connection.channel () #定义交换机, set type Directchannel.exchange_declare ( Exchange= ' Messages ', type= ' direct ') #从命令行获取路由键参数, if not, set to Inforoutings = Sys.argv[1:]if not routings:  routings = [ ' Info '] #生成临时队列, and bind to the switch, set the routing key result = Channel.queue_declare (exclusive=true) queue_name = result.method.queuefor Routing in routings:  channel.queue_bind (exchange= ' messages ',            queue=queue_name,            routing_key=routing) DEF callback (ch, method, properties, body):  print "[x] Received%r"% (body,) Channel.basic_consume (callback, Queue=q Ueue_name, no_ack=true) print ' [*] waiting for messages. To exit Press CTRL + C ' channel.start_consuming ()

Open two terminals, one running code python receive.py info Warning, indicating that only messages receiving info and warning are received. Another terminal running send.py, you can observe that the receiving terminal only received messages of info and warning. If you open multiple terminals to run receive.py and pass in different routing key parameters, you can see more obvious effects.

When the receive is correct at run time, you can use Rabbitmqctl list_bindings to view the binding situation.

Routing Key Fuzzy Matching
Routing key fuzzy matching, that is, you can use regular expressions, and the usual regular expression is different, here the words "#" means all, all the meaning; "*" matches only one word. Read the example and you'll see.

This is followed by the above example, or with send.py and receive.py to achieve the function of the routing key fuzzy matching. The send.py represents the sending side, and the receive.py represents the receiving end. The function of the instance is probably this: for example, you have a good friend, no matter happy, sad, work or life things can be said to her, there are some friends can share happy things, and some friends, you can put the unhappy things and she said.

send.py Code Analysis

Because the routing key fuzzy match, the switch type to set to topic, set to topic, you can use the #,* matching symbol.

#!/usr/bin/env python#coding=utf8import Pika connection = Pika. Blockingconnection (Pika. Connectionparameters (        ' localhost ')) channel = Connection.channel () #定义交换机, set type Topicchannel.exchange_declare ( Exchange= ' Messages ', type= ' topic ') #定义路由键routings = [' happy.work ', ' happy.life ', ' sad.work ', ' sad.life '] #将消息依次发送到交换机, and set the routing key for routing in routings: message  = '%s ' message. '% routing  channel.basic_publish (exchange= ' messages ',             routing_key=routing,             body=message)  print Message connection.close ()

The above example defines four types of messages that are easy to understand, do not explain, and then send them out in turn.

receive.py Code Analysis

Similarly, the type of switch should be set to topic. The function of receiving parameters from the command line is slightly adjusted, that is, no parameter times the wrong exit.

#!/usr/bin/env python#coding=utf8import pika, sys connection = Pika. Blockingconnection (Pika. Connectionparameters (        ' localhost ')) channel = Connection.channel () #定义交换机, set type Topicchannel.exchange_declare ( Exchange= ' Messages ', type= ' topic ') #从命令行获取路由参数, if not, the error exits routings = Sys.argv[1:]if not routings:  print >> Sys.stderr, "Usage:%s [Routing_key] ..."% (sys.argv[0],)  exit () #生成临时队列, and bind to switch, set routing key result = Channel.queue_ DECLARE (exclusive=true) queue_name = result.method.queuefor routing in routings:  channel.queue_bind (exchange= ' Messages ',            queue=queue_name,            routing_key=routing) def callback (ch, method, properties, body):  print "[x] Received%r "% (body,) Channel.basic_consume (callback, Queue=queue_name, no_ack=true) print ' [*] waiting for messages. To exit Press CTRL + C ' channel.start_consuming ()

Open four terminals, one run as follows, indicating that anything can and she says:

Python receive.py "#"

Another terminal runs as follows, indicating that you can share with her happy things:

Python receive.py "happy.*"

The third runs as follows, indicating that things on the job can be shared with her:

Python receive.py "*.work"

The last one runs Python send.py. The result is not difficult to imagine, it is not posted out.

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.