RABBITMQ PHP Tutorial-One

Source: Internet
Author: User
Tags autoload rabbitmq
RABBITMQ PHP tutorial-1

Introduction


RabbitMQ is a message broker. In essence, it accepts messages from producers, and delivers them to consumers. In-between, it can route, buffer, and persist the messages according to rules for you give it.

RabbitMQ is a message agent. Plainly, it receives messages from "producers" and sends them to "consumers". In this process, it can route, buffer, and persist messages based on the rules you have given.

RabbitMQ, and messaging in general, uses some jargon. (Common terminology)

  • producing means nothing more than sending. Sends messages is a producer. We'll draw it like this, with "P":

  • Production is nothing more than sending. A program that sends a message is a "producer" and we use "P" to represent it.
  • a queue is the name for a mailbox. It lives inside RabbitMQ. Although messages flow through RabbitMQ and your applications, they can is stored only inside a queue. A queue is not bound by any limits, it can store as many messages as you like-it ' s essentially an infinite buff Er. Many producers can send messages that go to one queue-many consumers can try to receive data from one queue. A queue would be drawn like this, with its name above it:

  • The queue is like the name of the mailbox. It is stored inside the RABBITMQ. Although the message flow runs through RABBITMQ and your application, it can only be stored in a queue. The queue is free of any restrictions, you can save as many messages as you want-the queue is essentially an infinity buffer. Multiple "Consumers" can send messages to a queue-multiple "consumers" can also receive messages from a queue. We do this to indicate a queue (below), with its name above.
  • consuming has a similar meaning to receiving. A consumer is a program this mostly waits to receive messages. On our drawings it's shown with "C":

  • consumption means receiving. A "consumer" is usually a program that waits for a message to be accepted. We use "C" to express.

Note that the producer, consumer, and broker does not have a to reside on the same machine; Indeed in the most applications they don ' t.

Note: Producers, consumers, and message agents (middlemen) do not have to be on a machine, indeed, most applications do.

"Hello World"

(using the Php-amqplib Client)

In this part of the tutorial we ' ll write both programs in PHP; A producer that sends a single message, and a consumer that receives messages and prints them out. We ' ll gloss over some of the detail in the Php-amqplib API, concentrating on this very simple thing just to get started. It ' s A "Hello world" of messaging.

In this strip, we will write two PHP programs, one to send a single message to the producer, and one to receive the message and print the consumer. We skipped over some of the Php-amqplib API details and focused on these simple things to open stave-a message to the Hello World program.

In the diagram below, "P" are our producer and "C" are our consumer. The box in the middle are a queue-a message buffer that RabbitMQ keeps on behalf of the consumer.

In the chart below, p is our producer and C is our consumer. The middle inner basket is a queue-a message buffer maintained by RABBITMQ.

[|||] (C) "src="/img/2014/04/04/141955269.png "height=" style= "border:0px" >

the php-amqplib client library

RabbitMQ speaks AMQP, which is an op En, general-purpose protocol for messaging. There is a number of clients for AMQP in many different languages. We'll use the Php-amqplib-tutorial.

The

RabbitMQ follows amqp--an open, multipurpose messaging protocol. There are also several AMQP clients in different languages. We'll use Php-amqplib. ~

Add a Composer.json file to your project: Add a Composer.json in your project as follows:

{" require ": {" Videlalvaro/php-amqplib ":" V2.1.0 "}} 

Provided you are composer installed, you can run the following: If you already have composer installed, you can execute the following command:

$ Composer.phar Install 

Now we have the php-amqplib installed, we can write some code.

Now Php-amqplib is finished, write some code.

Sending (send)

[|||]" Src= "/img/2014/04/04/141955270.png" height= "style=" border:0px ">

We ' ll call our message sender send.php and our message receiver receive.php. The sender would connect to RabbitMQ and send a single message and then exit.

Create a file send.php to send a message, receive.php to receive the message. The sender (send.php) connection RABBITMQ sends a message, and then exits the program.

In send.php, we need to include the library and use the necessary classes:

send.php, you need to include the necessary libraries and introduce the necessary classes.

Require_once __dir__. '/vendor/autoload.php '; use Phpamqplib\connection\amqpconnection;use phpamqplib\message\amqpmessage;

Then we can create a connection to the server:

Then create a connection that connects to the server.

$connection = new Amqpconnection (' localhost ', 5672, ' guest ', ' guest '); $channel = $connection->channel ();

The connection abstracts the socket connection, and takes care for protocol version negotiation and authentication and so O N for us. Here we connect to a broker on the local machine-hence the localhost. If we wanted to connect to a broker in a different machine we ' d simply specify the IT name or IP address here.

This connection helps us to do socket link, deal with protocol version negotiation and authentication. So we link to the local message broker (broker), because it's localhost. If you want to link a broker on a different machine, simply specify the name or IP address, just replace the above localhost.

Next we create a channel, which is where most of the API for getting things do resides.

Let's create a channel--most of the API's work is done here.

To send, we must declare a queue for us to send to; Then we can publish a message to the queue:

In order to be able to send a message, a queue must be declared. Then you can send a message to the.

$channel->queue_declare (' Hello ', False, False, False, false), $msg = new Amqpmessage (' Hello world! '); $channel->basic_publish ($msg, ' ', ' hello '); echo "[x] Sent ' Hello world! ' \ n ";

Declaring a queue is idempotent-it would only be created if it doesn ' t exist already. The message content is a byte array and so you can encode whatever your like there.

Declaring a queue to be idempotent-is created only if it does not exist. The message content is a byte array, so, you can code a bit of anything, put that replacement can be sent.

Lastly, we close the channel and the connection;

Finally, the channel and server connections are closed.

$channel->close (); $connection->close ();

Here ' s the whole send.php class. (This is the entire send.php class file)

Sending doesn ' t work! (Post a message)

If This was your first time using RabbitMQ and you don't see the "Sent" message then you'll be left scratching your head W Ondering what could is wrong. Maybe the broker was started without enough free disk space (by default it needs at least 1Gb free) and is therefore refus ing to accept messages. Check the broker logfile to confirm and reduce the limit if necessary. The configuration file documentation would show you what to Setdisk_free_limit.

If you use RABBITMQ for the first time and don't see the "sent (sent)" message, then the rest is scratching your head--for woolen? What's wrong? It is possible that the wood has enough hard disk space available at broker startup (at least 1G by default), so the message is rejected. Check the broker log file to determine if necessary, to adjust the limit value. This configuration file will tell you how to set the available hard drive limit values.

Receiving (Receive message)

That's it for our sender. Our receiver was pushed messages from RabbitMQ, so unlike the sender which publishes a single message, we'll keep it runnin G to listen for messages and print them out.

That's what the sender is all about. Receiver, as the name implies is to receive from the RABBITMQ push over the message, so unlike the sender who has a message will be finished.

We keep the receiver running to receive and print messages.

(C) "src="/img/2014/04/04/141955271.png "height=" style= "border:0px" >

The code (in receive.php) has almost the same include and uses as send:

The code for include and use in receive.php is almost the same as send.php.

Require_once __dir__. '/vendor/autoload.php '; use phpamqplib\connection\amqpconnection;

Setting up is the same as the sender; We open a connection and a channel, and declare the queue from which we ' re going to consume. Note this matches up with the queue, that is, send publishes to.

The setting also opens a connection and channel as above, declaring a queue where we want to consume (receive messages). Note that this should correspond to the declaration of the sender above.

$connection = new Amqpconnection (' localhost ', 5672, ' guest ', ' guest '); $channel = $connection->channel (); $channel- >queue_declare (' Hello ', False, False, false, false); Echo ' [*] waiting for messages. To exit Press CTRL + C ', "\ n";

Note that we declare the queue here, as well. Because we might start the receiver before the sender, we want to make sure the queue exists before we try to consume mess Ages from it.

Mainly here also we declared the queue. Because it is possible that we receive the message before the sender sends it, make sure to save it before we receive the message from it.

We ' re about to tell the server to deliver us the messages from the queue. We'll define a PHP callable that would receive the messages sent by the server. Keep in mind that messages is sent asynchronously from the server to the clients.

We have to tell the server to send us a message from the queue. Defines a callback to receive messages sent by the server. Remember, the message sent from the server to the client is asynchronous.

$callback = function ($msg) {  echo "[x] Received", $msg->body, "\ n";}; $channel->basic_consume (' Hello ', ' ', false, True, False, False, $callback), while (count ($channel->callbacks)) {    $channel->wait ();}

Our code would block while our $channel have callbacks. Whenever we receive a message Our$callback function would be passed the received message.

Since $channel has a callback, our code will block (listen to the message, not the bug), when we receive the message, the callback function will handle it.

Here's the whole receive.php class (Full receive.php class file)

Putting it all together (fitness!!!) )

Now we can run both scripts. In a terminal, run the sender:

Write all finished, run a chant, first run sender

$ PHP send.php

Then, run the receiver: and then run receiver.

$ PHP receive.php

The receiver would print the message it gets from the sender via RabbitMQ. The receiver would keep running, waiting for messages (use CTRL-C to stop it), so try running the sender from another termi Nal.

Inside, the receiver will print the message received from RABBITMQ, of course, the message is sent to RABBITMQ. The receiver will be here to kill, keep up with the message (use Ctrl-c to kill it), try to run sender at other terminals.

If you want to a check on the queue, try using Rabbitmqctl list_queues.

To see this queue, use Rabbitmqctl list_queues this command. (Inside A: Under the sbin/, oh, can't find the words)

Hello world! Hello, World ~ ~

Time to move over to Part 2 and build a simple work queue. (Please look forward to, OH Roar roar ~ ~)

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