Home >Backend Development >Python Tutorial >Python operates the RabbitMQ server to implement message queue routing
RabbitMQ is a message queue server. Here we look at the server-side environment of Python+Pika+RabbitMQ and see how to use Python to operate the RabbitMQ server to implement the routing function of the message queue.
Python uses the Pika library (installation :sudo pip install pika) can operate the RabbitMQ message queue server (installation: sudo apt-get install rabbitmq-server). Here we take a look at the MQ-related routing functions.
Implementation of routing keys
For example, there is a scenario where messages need to be sent to all receivers, but if you need to freely customize, some messages are sent to some of the receivers. , some messages are sent to other receivers, what should we do? In this case, routing keys are used.
The working principle of the routing key: When the message queue of each receiving end is bound to the switch, the corresponding routing key can be set. When the sender sends information through the switch, it can specify the routing key, and the switch will send the message to the corresponding message queue based on the routing key, so that the receiving end can receive the message.
Following the previous article, we still use send.py and receive.py to simulate the function of routing keys. send.py represents the sending end, and receive.py represents the receiving end. The function of the instance is to send three levels of information: info, warning, and error to different receiving ends.
send.py code analysis
#!/usr/bin/env python #coding=utf8 import pika connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = connection.channel() #定义交换机,设置类型为direct channel.exchange_declare(exchange='messages', type='direct') #定义三个路由键 routings = ['info', 'warning', 'error'] #将消息依次发送到交换机,并设置路由键 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=utf8 import pika, sys connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = connection.channel() #定义交换机,设置类型为direct channel.exchange_declare(exchange='messages', type='direct') #从命令行获取路由键参数,如果没有,则设置为info routings = sys.argv[1:] if not routings: routings = ['info'] #生成临时队列,并绑定到交换机上,设置路由键 result = channel.queue_declare(exclusive=True) queue_name = result.method.queue for 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 runs the code python receive.py info warning, which means that only info and warning messages are received. Run send.py on another terminal, and you can observe that the receiving terminal only receives info and warning messages. If you open multiple terminals and run receive.py and pass in different routing key parameters, you can see more obvious effects.
When the receiving end is running, you can use rabbitmqctl list_bindings to view the binding status.
Routing key fuzzy matching
Routing key fuzzy matching means that you can use regular expressions, which is different from commonly used regular expressions. Here "#" means all, all. ; "*" only matches one word. You will understand after reading the examples.
Following the above example, send.py and receive.py are still used to implement the fuzzy matching function of routing keys. send.py represents the sending end, and receive.py represents the receiving end. The function of the example is roughly as follows: For example, if you have a close friend, you can talk to her about happiness, sadness, work or life; there are also some friends with whom you can share happy things; and there are some friends with whom you can share happy things. You can talk to her about unhappy things.
send.py code analysis
Because routing key fuzzy matching is required, the switch type must be set to topic. If set to topic, you can use the matching symbols of # and *.
#!/usr/bin/env python #coding=utf8 import pika connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = connection.channel() #定义交换机,设置类型为topic channel.exchange_declare(exchange='messages', type='topic') #定义路由键 routings = ['happy.work', 'happy.life', 'sad.work', 'sad.life'] #将消息依次发送到交换机,并设定路由键 for routing in routings: message = '%s message.' % routing channel.basic_publish(exchange='messages', routing_key=routing, body=message) print message connection.close()
In the above example, four types of messages are defined. They are easy to understand and will not be explained. They are then sent out in sequence.
receive.py code analysis
Similarly, the type of switch must be set to topic. The function of receiving parameters from the command line has been slightly adjusted, that is, it will exit with an error if there are no parameters.
#!/usr/bin/env python #coding=utf8 import pika, sys connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = connection.channel() #定义交换机,设置类型为topic channel.exchange_declare(exchange='messages', type='topic') #从命令行获取路由参数,如果没有,则报错退出 routings = sys.argv[1:] if not routings: print >> sys.stderr, "Usage: %s [routing_key]..." % (sys.argv[0],) exit() #生成临时队列,并绑定到交换机上,设置路由键 result = channel.queue_declare(exclusive=True) queue_name = result.method.queue for 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 runs as follows, indicating that you can talk to her about anything:
python receive.py "#"
The other terminal runs as follows, indicating that you can share happy things with her:
python receive.py "happy.*"
The third terminal runs as follows, indicating that you can share happy things with her: Things can be shared with her:
python receive.py "*.work"
The last one runs python send.py. The result is easy to imagine, so I won’t post it here.
For more articles related to Python operating RabbitMQ server to implement message queue routing, please pay attention to the PHP Chinese website!