RABBITMQ and PHP (i)--RABBITMQ principle and Operation example

Source: Internet
Author: User
RABBITMQ is a popular open source Message Queuing system, developed in Erlang language, and fully implements AMQP (Advanced Message Queuing protocol). Website in: http://www.rabbitmq.com/with tutorials and instance code (Python and Java).
7af40ad162d9f2d36b6bf89fa8ec8a136327cc4c
The AMPQ protocol is conceptually more complex in order to meet the needs of various message queues. First, the RABBITMQ boot default is no configuration, requires the client to connect up, set up the switch and so on to work. By not figuring out these basic concepts, it is easy to create problems later in the programming.
1.vhosts: Virtual host.
A RABBITMQ entity can have more than one vhosts, and the user and permission settings are dependent on vhosts. For the general PHP application, do not need user permission settings, directly using the default is the existence of "/" can be, the user can use the default is the existence of "guest." A simple example of configuration:
$conn _args = Array (
' Host ' = ' 127.0.0.1 ',
' Port ' = ' 5672 ',
' Login ' = ' guest ',
' Password ' = ' guest ',
' Vhost ' = '/'
);
2.connection and Channel: connections and channels
Connection refers to a physical connection, a client has a connection to a server, and a connection can be constructed with multiple channel, which can be understood as a logical connection. In the case of general application, there is a channel sufficient to create more channel. Example code:
Creating Connections and Channel
$conn = new Amqpconnection ($conn _args);
if (! $conn->connect ()) {
Die ("Cannot connect to the broker!\n");
}
$channel = new Amqpchannel ($conn);
3.exchange and Routingkey: Switches and routing keys
In order to differentiate different types of messages, two concepts of switch and route are set up. For example, a type a message is sent to a switch named ' C1 ', which sends a switch of type B to ' C2 '. When a client connects to a C1 processing queue message, it only takes a type a message. Further, if a type of message is also very much, you need to further refine the distinction, such as a client processing only a type of message for K users in the message, Routingkey is to do this purpose.
$e _name = ' e_linvo '; Switch name
$k _route = Array (0=> ' key_1 ', 1=> ' key_2 '); Route key
Create a switch
$ex = new Amqpexchange ($channel);
$ex->setname ($e _name);
$ex->settype (Amqp_ex_type_direct); Direct type
$ex->setflags (amqp_durable); Persistence of
echo "Exchange Status:" $ex->declare (). " \ n ";
for ($i =0; $i <5; + + $i) {
echo "Send Message:". $ex->publish ($message. Date (' H:i:s '), $k _route[i%2]). " \ n ";
}
As you can see from the above code, when you send a message, it is sufficient to have a "switch". As for there is no corresponding processing queue behind the switch, the sender is not the tube. The Routingkey can be an empty string. In the example, I used two keys to send the message alternately to make it easier to understand the role of Routingkey.
For switches, there are two important concepts:
A, type. There are three types: the fanout type is the simplest, this model ignores the Routingkey;direct type is the most used, uses the determined routingkey. In this model, when the message is received, the binding ' key_1 ' receives only key_1 messages, and the last is topic, which is similar to direct, but supports wildcard matching, such as ' key_* ', which will accept Key_1 and key_2. Topic looks good, but it may lead to a non-rigorous, so it is recommended to use direct.
B, persistent. A persistent switch is specified and can be rebuilt at reboot, otherwise the client is required to re-declare the build.
A particularly explicit concept is needed: The persistence of the switch is not equal to the persistence of the message. Only messages in the persistent queue can be persisted, and if there is no queue, the message is not stored anywhere, and the message itself has a persistent flag on delivery, and the default post to the persistent switch in PHP is a persistent message, not specifically specified.
4.queue: Queue
Speaking so much, it is only in the queue. In fact, the queue is only for the receiver (consumer), which is created by the receiver on demand. Only when the queue is created does the switch send the newly received message to the queue, and the switch is not put in the message before the queue is created. In other words, all messages that are sent are discarded before the queue is established. The following figure is clearer than the official figure of RABBITMQ--queue is part of the receivemessage.
024f78f0f736afc37053e415b219ebc4b7451266
Next look at the example of creating a queue and receiving messages:
$e _name = ' e_linvo '; Switch name
$q _name = ' q_linvo '; Queue name
$k _route = "; Route key
Creating Connections and Channel
$conn = new Amqpconnection ($conn _args);
if (! $conn->connect ()) {
Die ("Cannot connect to the broker!\n");
}
$channel = new Amqpchannel ($conn);
Create a switch
$ex = new Amqpexchange ($channel);
$ex->setname ($e _name);
$ex->settype (Amqp_ex_type_direct); Direct type
$ex->setflags (amqp_durable); Persistence of
echo "Exchange Status:" $ex->declare (). " \ n ";
Create a queue
$q = new Amqpqueue ($channel);
$q->setname ($q _name);
$q->setflags (amqp_durable); Persistence of
Binds the switch to the queue and specifies the routing key
Echo ' Queue Bind: '. $q->bind ($e _name, $k _route). " \ n ";
Blocking mode receiving messages
echo "message:\n";
$q->consume (' ProcessMessage ', amqp_autoack); Automatic ACK response
$conn->disconnect ();
/**
* Consumption callback function
* Processing messages
*/
function ProcessMessage ($envelope, $queue) {
Var_dump ($envelope->getroutingkey);
$msg = $envelope->getbody ();
echo $msg. " \ n "; Processing messages
}
As you can see from the example above, the switch can be created either by the message sender or by the message consumer.
After you create a queue (LINE:20), you need to bind the queue to the switch (line:25) queue to work, Routingkey is also specified here. Some of the information written Bindingkey, in fact, one thing, make two noun is easy to confuse.
The processing of messages is available in two ways:
A, disposable. Use the $q->get ([...]) to return immediately, regardless of whether the message is taken or not, and in general the use of polling to process the message queue is in this way;
B, block. With $q->consum (callback, [...]) the program enters a continuous listening state, and each time a message is received, the function specified by callback is called once, until a callback function returns false to end.
About callback, here are a few more words: PHP Call_back is to support the use of arrays, such as: $c = new MyClass (); $c->counter = 100; $q->consume (Array ($c, ' myfunc ')) so that you can invoke the processing class that you write. The MyFunc parameter definition in MyClass is the same as in the previous example ProcessMessage.
In the above example, the use of $routingkey = "means that all messages are received. We can change it to $routingkey = ' key_1 ', and we can see that only the contents of Routingkey are set to key_1 in the results.
Note: Routingkey = ' key_1 ' with routingkey = ' key_2 ' is a two different queue. Assume that both CLIENT1 and Client2 are connected to the Key_1 queue, and a message is client1 processed and will not be client2 processed. and Routingkey = "is the alternative, Client_all bound to", the message is all processed, CLIENT1 and Client2 there is no message.
In programming, you need to plan the name of exchange and how to use the key to separate different types of tags and insert the sending message code where the message is generated. Back-end processing, you can start one or more clients for each key to improve the real-time nature of message processing. How to use PHP for multi-threaded message processing is described in the next section.
For more information models, refer to: http://www.rabbitmq.com/tutorials/tutorial-two-python.html
B03533fa828ba61e15fc0e5f4034970a304e59b4
Http://nonfu.me/p/8833.html

The above describes the RABBITMQ and PHP (a)--RABBITMQ principles and operating examples, including aspects of the content, I hope to be interested in the PHP tutorial friends helpful.

  • 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.