Translation-php RabbitMQ Tutorial-3

Source: Internet
Author: User
Tags autoload emit rabbitmq rabbitmq tutorial amq

Publish/subscribe (Publish/Subscribe mode)

(using Php-amqplib)

In the previous tutorial we created a work queue. The assumption behind a work queue is, each task was delivered to exactly one worker. In this part we'll do something completely different--we'll deliver a message to multiple consumers. This pattern is known as "Publish/subscribe".

On a chop, we set up a Task Force column. The implicit assumption is that a task is sent only to a worker. This time we're going to do something completely different?? Dispatch information to multiple consumers, this mode is called "Publish/Subscribe".

To illustrate the pattern, we ' re going to build a simple logging system. It would consist of programs-the first would emit log messages and the second would receive and print them.

To illustrate this pattern, let's build a simple log system. It consists of two programs?? The first one to publish the log messages, and the second to receive and print the messages.

In our logging system every running copy of the receiver program would get the messages. That's the able to run one receiver and direct the logs to disk; And at the same time we'll be able to run another receiver and see the logs in the screen.

In our log system, the runtime copy of each receiving program can receive a message sent by the sender (sender). So we can run a receiver program to write the log to the hard disk while running another on-screen view of the message.

Essentially, published log messages is going to being broadcast to all the receivers.

Essentially, the published message will be broadcast to all receiving programs (listeners).

Exchanges (Exchanger)

In previous parts of the tutorial we sent and received messages to and from a queue. Now it's time to introduce the full messaging model in Rabbit.

In the previous section, we sent and received messages from the queue. Now it's time to introduce the complete message delivery pattern for RABBITMQ.

Let's quickly go over what we covered in the previous tutorials:

Let's take a quick look at what's involved.

  • A producer is a user application that sends messages.
  • Producer is a user program that sends messages
  • A queue is a buffer, that stores messages.
  • Queue is the buffer used to store messages
  • A consumer is a user application that receives messages.
  • A consumer is a user program that receives messages
  • The core idea in the messaging model in RabbitMQ is, the producer never sends any messages directly to a queue. Actually, quite often the producer doesn ' t even know if a message would be delivered to any queue at all.

    The core idea of this message-passing pattern is that producers never send any messages directly to the queue. In fact, many times producers don't even know if the message will be

    Passed to the queue.

    Instead, the producer can only be send messages to an exchange. An exchange is a very simple thing. On one side it receives messages from producers and the other side it pushes them to queues. The exchange must know exactly what does with a message it receives. Should it is appended to a particular queue? Should it is appended to many queues? Or should it get discarded. The rules for is defined by the Exchange type.

    Instead, the producer simply sends the message to the exchanger (Exchange). The switch is a very simple thing. On the one hand it receives messages from producers, on the other hand

    It pushes the message to the queue. The exchanger must clearly know how to handle the received message. Should this message be appended to a specific queue? or append to multiple queues? Or it should be discarded. To do this, we can define the rules through the Exchange type (Exchange type).

    There is a few exchange types Available:direct, topic, headers and fanout. We ' ll focus on the last one--the fanout. Let's create an exchange of this type, and call it logs:

    The types of exchangers that are available in the hub: Direct,topic,headers and Fanout. Let's take a look at the last--fanout. Creating a switch of this type is called "Logs".

    $channel->exchange_declare (' Logs ', ' fanout ', False, false, false);

    The Fanout exchange is very simple. As can probably guess from the name, it just broadcasts all the messages it receives to all the queues it knows. And that's exactly what we need for our logger.

    The fanout exchanger doubles as simple. From its name you may have guessed that it is to broadcast all the received messages to all known queues. This happens to be what our journaling system wants.

    Listing Exchanges (Exchanger list)

    To list the exchanges on the serve you can run the ever useful rabbitmqctl:

    You can still run rabbitmqctl to list the switches in the service (you can also see the type OH).

    $ sudo rabbitmqctl list_exchangeslisting exchanges ...        Directamq.direct      directamq.fanout      fanoutamq.headers     headersamq.match       headersamq.rabbitmq.log        topicamq.rabbitmq.trace      topicamq.topic       topiclogs    fanout...done.

    In this list there is some amq.* exchanges and the default (unnamed) Exchange. These is created by default, but it's unlikely you'll need to use them at the moment.

    There are some switches in the list that start with amq.* and the default (no name inside) switch. They are created by default. But now we're not likely to use that.

    Nameless Exchange (John Doe switch)

    In previous parts of the tutorial we knew nothing on exchanges, but still were able to send messages to queues. That was possible because we were using a default exchange, which are identified by the empty string ("").

    Before that, we knew nothing about the exchanger, but still could send a message to the queue (for Meow?). )。 There's a good chance that we're using the default switch, which is the one defined with the empty string.

    Recall how we published a message before:

    Recall how we posted the message before:

    $channel->basic_publish ($msg, ', ' hello ');

    Here we use the default or nameless Exchange:messages is routed to the queue with the name specified by Routing_key, if It exists. The routing key is the second argument to Basic_publish

    We're here with the default or John Doe switch: If there is a routing_key, the message is routed to the Routing_key specified queue, and Routing_key is the second parameter of Basic_publish.

    Now, we can publish to our named Exchange instead:

    Now, we're releasing a switch with a name.

    $channel->exchange_declare (' Logs ', ' fanout ', False, false, false); $channel->basic_publish ($msg, ' logs ');

    Temporary queues (temporary queue)

    As may remember previously we were using queues which had a specified name (Remember Hello and task_queue?). Being able to name a queue is crucial for us – we needed to point the workers to the same queue. Giving A queue a name is important if you want to share the queue between producers and consumers.

    As you may recall, we used a queue called Hello and task_queue before. Naming queues is important to us?? We have to point the worker to the same queue (the same name). When you want to share a queue between producers and consumers, naming a queue name is especially important.

    But that's not the case for our logger. We want to hear on all logs messages, not just a subset of them. We ' re also interested only in currently flowing messages isn't in the old ones. To solve that we need the things.

    But that's not what our log system is going to use. We are going to receive all the log messages, not a part. Again, we are only interested in the latest news, not the old ones. Two things to solve the problem.

    Firstly, whenever we connect to Rabbit we need a fresh, empty queue. To does this we could create a queue with a random name, or, even better-let the server choose a random queue name for us.

    First of all, we need a new, empty queue whenever we link to rabbit. To do this, we can create a queue of random names, or,

    What's even better? Let the RABBITMQ service choose a random queue for us.

    Secondly, once we disconnect the consumer the queue should be automatically deleted.

    Period, the queue should be automatically deleted once the consumer's connection is disconnected.

    In the Php-amqplib client, when we supply queue name as a empty string, we create a non-durable queue with a generated NA Me

    In the Php-amqplib client, each time a queue with a null character is created, a non-persistent queue is created, with the system assigning a name.

    List ($queue _name,,) = $channel->queue_declare ("");

    When the method is returns, the $queue _name variable contains a random queue name generated by RabbitMQ. For example it could look like AMQ.GEN-JZTY20BRGKO-HJMUJJ0WLG.

    $queue _name receives a queue name that is randomly generated by the RABBITMQ. For example: It may look like AMQ.GEN-JZTY20BRGKO-HJMUJJ0WLG.

    When the connection that declared it closes, the queue would be a deleted because it is declared as exclusive.

    When the connection is closed, it is deleted because the queue is declared unique.

    Bindings (Bundle/BIND)

    We ' ve already created a fanout exchange and a queue. Now we need to tell the exchange to send messages to our queue. That relationship between Exchange and a queue is called a binding.

    We have created a fanout type of exchanger and a queue. Now we have to tell the exchanger to send a message to this queue. Between this exchanger and the queue

    Relationships are called "bundles."

    $channel->queue_bind ($queue _name, ' logs ');

    From now on the logs exchange would append messages to our queue.

    From now on, the logs exchanger will append the information to our queue.

    Listing Bindings (Bundle list)

    You can list existing bindings using, you guessed it, Rabbitmqctl list_bindings.

    Already guessed, use Rabbitmqctl list_bindings to list the existing bundles.

    Putting it all together (fitness!!!) Come again!! ha haha)

    The producer program, which emits logs messages, doesn ' t look much different from the previous tutorial. The most important change is, we now want to publish messages to our logs exchange instead of the Nameless one. We need to supply a routing_key when sending, but it value is ignored for fanout exchanges. Here goes the code for emit_log.php script:

    The producer program that sent the log message does not look much different from the previous. The biggest difference is now we're going to send a message to the logs switch instead of the anonymous one.

    When sending, we need to provide a routing_key, but for the fanout switch, its value is ignored. Take a look at the emit_log.php script:

     
      Channel (); $channel->exchange_declare (' Logs ', ' fanout ', False, false, false); $data = Implode (", Array_slice ($ARGV, 1)); if (empty ($data)) $data = "Info:hello world!"; $msg = new Amqpmessage ($data), $channel->basic_publish ($msg, ' logs '), echo "[x] Sent", $data, "\ n"; $channel->close (); $connection->close ();? >

    (emit_log.php Source)

    As you see, after establishing the connection we declared the exchange. This step is necessary as publishing to a non-existing exchange is forbidden.

    As you can see, we declare a switch after we establish the connection. This step is necessary because it is forbidden to publish the message to a non-existent exchanger.

    The messages would be lost if no queue was bound to the exchange yet, but that's okay for us; If no consumer is listening yet we can safely discard the message.

    However, if no queue is bundled into a switch, the message will be lost, but it doesn't matter to us. We can safely discard this message if there is no consumer to listen to.

    The code for receive_logs.php: (receive_logs.php code)

     
      Channel (); $channel->exchange_declare (' Logs ', ' fanout ', False, false, false); list ($queue _name,,) = $channel Queue_declare ("", False, False, true, false); $channel->queue_bind ($queue _name, ' logs '); Echo ' [*] waiting for logs. To exit Press CTRL + C ', "\ n"; $callback = function ($msg) {  echo ' [x] ', $msg->body, "\ n";}; $channel->basic_consume ($queue _name, ", False, True, False, False, $callback), while (Count ($channel->callbacks ) {    $channel->wait ();} $channel->close (); $connection->close ();? >

    (receive_logs.php Source)

    If you want to save logs to a file, just open a console and type:

    If you want to save the log to a file, open the console and type:

    $ php receive_logs.php > Logs_from_rabbit.log

    If you wish to see the logs in your screen, spawn a new terminal and run:

    If you want to view the logs on the screen, open a new terminal and then run:

    $ PHP receive_logs.php

    And of course, to emit logs type:

    Of course, to publish the message Please enter:

    $ PHP emit_log.php

    Using Rabbitmqctl list_bindings You can verify that the code actually creates bindings and queues as we want. With the RECEIVE_LOGS.RB programs running you should see something like:

    With Rabbitmqctl list_bindings You can verify that the code has the wood and really follow our expectations to create bundles and queues. Run both receive_logs.php (here the official document copy is wrong, the. RB Ruby file extension has not been changed back), and there should be something like this:

    $ sudo rabbitmqctl list_bindingslisting bindings ... logs    exchange        AMQ.GEN-JZTY20BRGKO-HJMUJJ0WLG  queue           []logs    Exchange        amq.gen-vso0pvvyiril2wov3i48yg  queue           []...done.

    The interpretation of the result is straightforward:data from Exchange logs goes to a queues with server-assigned names . And that ' s exactly, what we intended.

    The result is straightforward: the data goes from the logs switch to the two queues named by the RABBITMQ service. This is the exact same as we intended.

    To find out how to listen for a subset of messages, let's move on to tutorial 4

    To know how to listen to some of the news, please listen to tell ~~~~~~~~~~~:)

  • Related Article

    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.