Use Python to operate the RabbitMQ server to implement message queue routing

Source: Internet
Author: User
RabbitMQ is a message queue server. here we are targeting the server environment of Python + Pika + RabbitMQ, let's take a look at how to use Python to operate the RabbitMQ server to implement the message queue routing function. RabbitMQ is a message queue server. here we are targeting the server environment of Python + Pika + RabbitMQ, let's take a look at how to use Python to operate the RabbitMQ server to implement the message queue routing function.

Python uses the Pika Library (install: sudo pip install pika) to operate the RabbitMQ message queue server (install: sudo apt-get install rabbitmq-server ), here we will look at the MQ-related routing functions.

Route key implementation

For example, there is a scenario where messages need to be sent to all receivers, but if you need to customize them, some messages are sent to some receivers, and some messages are sent to other receivers, what should you do? In this case, the route key is required.

How the route key works: When the message queue of each acceptor is bound to a vSwitch, you can set the corresponding route key. When sending a message through a vSwitch, the sender can specify the routing key. the vSwitch sends the message to the corresponding message queue based on the routing key, so that the receiver can receive the message.

In the previous article, we used send. py and receive. py to simulate the routing key function. Send. py indicates the sender, and receive. py indicates the receiver. The function of an instance is to send information at the info, warning, and error levels to different receivers.

Send. py code analysis

#! /Usr/bin/env python # coding = utf8import pika connection = pika. blockingConnection (pika. connectionParameters ('localhost') channel = connection. channel () # define the switch and set the type to directchannel. exchange_declare (exchange = 'messages ', type = 'direct') # define three route keys routings = ['info', 'warning ', 'error'] # send messages to the switch in sequence, and set the route 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 () # define the switch and set the type to directchannel. exchange_declare (exchange = 'messages ', type = 'direct') # obtain the route key parameter from the command line. if not, set it to inforoutings = sys. argv [1:] if not routings: routings = ['info'] # generate a temporary queue and bind it to the vSwitch. set the route 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 two terminals. one running code python receive. py info warning indicates that only messages of info and warning are received. Run send. py on another terminal. you can see that the receiving terminal only receives messages of info and warning. If you open multiple terminals to run receive. py and input different route key parameters, you can see more obvious results.

When the receiving end is running, you can use rabbitmqctl list_bindings to view the binding status.

Fuzzy match of route keys
Fuzzy match of the route key means that you can use a regular expression, which is different from a common regular expression. here, "#" indicates all and all meanings. "*" only matches one word. After reading the example, you can understand it.

In the above example, we still use send. py and receive. py to implement fuzzy matching of route keys. Send. py indicates the sender, and receive. py indicates the receiver. The function of the instance is like this: for example, if you have a good friend, you can tell her whether you are happy, sad, at work or in your life. some friends can share happy things; some friends can tell her unhappy things.

Send. py code analysis

Because you need to perform fuzzy match on the route key, you can use the matching symbols # and * to set the switch type to topic and topic.

#! /Usr/bin/env python # coding = utf8import pika connection = pika. blockingConnection (pika. connectionParameters ('localhost') channel = connection. channel () # defines the switch and sets the type to topicchannel. exchange_declare (exchange = 'messages ', type = 'topic') # define the route key routings = ['Happy. work', 'Happy. life ', 'Sad. work', 'Sad. life '] # send messages to the switch in sequence, and set the route key for routing in routings: message =' % s message. '% routing channel. basic_publish (exchange = 'messages ', routing_key = routing, body = message) print message connection. close ()

In the preceding example, four types of messages are defined, which are easy to understand and can be sent out in sequence.

Receive. py code analysis

Similarly, you can set the switch type to topic. The function of receiving parameters from the command line is slightly adjusted, that is, if there is no parameter, the system returns an error and exits.

#! /Usr/bin/env python # coding = utf8import pika, sys connection = pika. blockingConnection (pika. connectionParameters ('localhost') channel = connection. channel () # defines the switch and sets the type to topicchannel. exchange_declare (exchange = 'messages ', type = 'topic') # obtain the route parameters from the command line. if not, an error is returned and the system exits. argv [1:] if not routings: print> sys. stderr, "Usage: % s [routing_key]... "% (sys. argv [0],) exit () # generate a temporary queue and bind it to the vSwitch. set the route 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 and run one of them as follows, which means everything can be said to her:

python receive.py "#"

Another terminal is running as follows, which means you can share something fun with her:

python receive.py "happy.*"

The third running is as follows, indicating that you can share things at work with her:

python receive.py "*.work"

Run python send. py. The results can be easily imagined, so they will not be posted.

For more articles about how to use Python to operate the RabbitMQ server to implement message queue routing, refer to PHP!

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.