RabbitMQ and PHP

Source: Internet
Author: User
Tags rabbitmq
RabbitMQ and PHP have you ever met that some data needs to be synchronized through scheduled tasks between two (multiple) systems? Are you worried and struggling with the problems of mutual calls and communication between different processes of heterogeneous systems? If yes, congratulations, MNS allows you to easily solve these problems. Message service is good at solving data exchange (message notification/communication) among multiple systems and heterogeneous systems. you can also use it for inter-system service mutual calling (RPC ). The RabbitMQ introduced in this article is one of the most popular message-oriented middleware.

About RabbitMQ

AMQPAdvanced Message Queuing Protocol is an open standard for application layer protocols and is designed for Message-oriented middleware. Message-oriented middleware is mainly used for decoupling between components. message senders do not need to know the existence of message users, and vice versa.

AMQP features message-oriented, queue-oriented, routing (including point-to-point and publish/subscribe), reliability, and security.

RabbitMQIs an open-source AMQP implementation. the server side is written in Erlang and supports multiple clients, such as Python, Ruby, and ,. NET, Java, JMS, C, PHP, ActionScript, XMPP, STOMP, etc. AJAX is supported. It is used to store and forward messages in a distributed system, and has good performance in terms of ease of use, scalability, and high availability. Website on: http://www.rabbitmq.com/with various language tutorials and instance code

In order to meet the requirements of various message queues, AMPQ is more complicated in terms of concept. understanding these concepts is the basis for using RabbitMQ.

Vhosts: virtual host

Virtual host: a virtual host holds a group of switches, queues, and bindings. Why do we need multiple virtual hosts? In RabbitMQ, users can only control permissions at the granularity of virtual hosts. Therefore, to prohibit Group A from accessing vswitches/queues/bindings of Group B, you must create A virtual host for Group A and Group B respectively. Each RabbitMQ server has a default virtual host "/".

A Server of RabbitMQ can have multiple vhosts. the user and permission settings are attached to vhosts. For common PHP applications, you do not need to set user permissions. you can simply use the "/" that exists by default. you can use the "guest" that exists by default ". A simple configuration example:

$conn_args = array(    'host' => '127.0.0.1',    'port' => '5672',    'login' => 'guest',    'password' => 'guest',    'vhost'=>'/');
Connection and channel: connection and channel

A connection refers to a physical connection. a client and a server have a connection. a connection can establish multiple channels, which can be understood as a logical connection. In general, it is enough to have a channel, and no more channels need to be created. Sample code:

// Create a connection and channel $ conn = new AMQPConnection ($ conn_args); if (! $ Conn-> connect () {die ("Cannot connect to the broker! \ N ") ;}$ channel = new AMQPChannel ($ conn );
Exchange and routingkey: switch and route key

In order to distinguish different types of messages, two concepts are set: Exchange switch and Route. For example, send A message of Type A to A switch named 'C1', and send A message of type B to A switch of 'C2. When the client connects to C1 to process the queue message, only A type message is obtained. Further, if there are too many messages of the type, you need to further differentiate them. for example, if A client only processes messages of the K user in the message of the type, the routingkey is used for this purpose.

$ E_name = 'e _ linvo '; // switch name $ k_route = array (0 => 'key _ 1', 1 => 'key _ 2 '); // route key // create vSwitch $ ex = new AMQPExchange ($ channel); $ ex-> setName ($ e_name); $ ex-> setType (AMQP_EX_TYPE_DIRECT ); // direct Type $ ex-> setFlags (AMQP_DURABLE); // persistent 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 ";}

The code above shows that when a message is sent, it is enough to have a "switch. The sender does not need to worry about whether there is a corresponding processing queue behind the switch. Routingkey can be a null string. In the example, I used two keys to send messages alternately, so that the role of routingkey can be better understood below.

Vswitches have two important concepts:

Exchange: it can be understood as a route program with a route table. Each message has a routing key, which is a simple string. A vSwitch has a series of binding rules (routes ). You can have multiple vswitches. Multiple queues can be bound to the same vSwitch, and multiple vswitches can also be bound to the same queue. (Many-to-many relationship)

A, type. There are three types:

1. Fanout Exchange (do not process the route key): A message sent to the switch will be forwarded to all the queues bound to the switch. Fanout switches send the fastest messages.

2. direct Exchange (processing route key): if a queue is bound to this switch and the current required route key is X, only messages with the route key X will be forwarded by this queue.

3. topic Exchange (fuzzy processing can be used to match a route key and a certain mode): the symbol "#" indicates that 0 or more words are matched, and the symbol "*" indicates that not many words are matched.

Summary: The Fanout type is the simplest. this model ignores the routingkey. the Direct type is the most commonly used, and the determined routingkey is used. In this model, when receiving a message, bind 'key _ 1' to only receive the key_1 message. The last one is the Topic. this mode is similar to Direct, but supports wildcard matching, for example: 'key _ * ', key_1 and key_2 are accepted. The Topic looks good, but it may lead to less rigorous things. Therefore, Direct is recommended.

B. persistence. If a persistent vSwitch is specified, it can be rebuilt only when it is restarted. Otherwise, the client must re-declare and generate the vSwitch.

The persistence of vswitches is not the same as message persistence. Only messages in a persistent queue can be persisted. without a queue, messages are stored in no place. messages themselves also have a persistence mark during delivery, by default, messages delivered to persistent switches in PHP are persistent messages and do not need to be specified.

4. queue: queue

After talking about this, we can talk about queues. In fact, the queue is only for the receiver (consumer) and is created by the receiver as needed. Only when a queue is created will the switch send the newly received message to the queue. the switch will not include the message before the queue is created. In other words, before a queue is established, all messages sent are discarded. The figure below is clearer than the official RabbitMQ figure-Queue is part of ReceiveMessage.

Next, let's take a 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 // create a connection and channel $ conn = new AMQPConnection ($ conn_args); if (! $ Conn-> connect () {die ("Cannot connect to the broker! \ N ") ;}$ channel = new AMQPChannel ($ conn); // Create a vSwitch $ ex = new AMQPExchange ($ channel); $ ex-> setName ($ e_name ); $ ex-> setType (AMQP_EX_TYPE_DIRECT); // direct Type $ ex-> setFlags (AMQP_DURABLE); // persistent echo "Exchange Status :". $ ex-> declare (). "\ n"; // Create a queue $ q = new AMQPQueue ($ channel); $ q-> setName ($ q_name); $ q-> setFlags (AMQP_DURABLE ); // persistent // Bind the vSwitch and Queue, and specify the route key echo 'queue Bind :'. $ q-> bind ($ e_name, $ k_route ). "\ n"; // echo "Message: \ n" in blocking mode; $ q-> consume ('processmessage', AMQP_AUTOACK ); // automatic ACK response $ conn-> disconnect ();/*** consumption callback function * processes the message */function processMessage ($ envelope, $ queue) {var_dump ($ envelope-> getRoutingKey); $ msg = $ envelope-> getBody (); echo $ msg. "\ n"; // process the message}

As shown in the preceding example, a vSwitch can be created either by the message sender or by the message consumer.

After creating a queue (line: 20), you need to bind the queue to the line: 25 queue on the switch to work. The routingkey is also specified here. Some documents are written as bindingkey. In fact, it is easy to confuse the two nouns.

There are two ways to process messages:

A, one-time. $ Q-> get ([...]) is used to return immediately no matter the message cannot be obtained. this method is usually used to process the message queue by polling;

B. blocking. Use $ q-> consum (callback, [...]) the program enters the continuous listening state. each time a message is received, the function specified by callback is called once until a callback function returns FALSE.

For more information about callback, PHP call_back supports arrays, for example, $ c = new MyClass (); $ c-> counter = 100; $ q-> consume (array ($ c, 'myfunc') so that you can call your own processing class. The parameter definition of myfunc in MyClass is the same as processMessage in the previous example.

In the preceding example, $ routingkey = "is used to receive all messages. We can change it to $ routingkey = 'key _ 1'. we can see that only the content with the routingkey set to key_1 is displayed in the result.

Note: routingkey = 'key _ 1' and routingkey = 'key _ 2' are two different queues. Assume that both client1 and client2 are connected to the key_1 queue. after a message is processed by client1, it is not processed by client2. The routingkey = "is an alternative, and client_all is bound to". after all messages are processed, no messages will be sent to client1 and client2.

In programming, you need to plan the exchange name and how to use the key to separate different types of tags and insert the message sending code where the message is generated. Backend processing: one or more clients can be started for each key to improve the timeliness of message processing. The following section describes how to use PHP to process multi-threaded messages.

For more message models, see: http://www.rabbitmq.com/tutorials/tutorial-one-php.html

Install the basic environment on which erlang depends
# Operating system: CentOS release 6.2yum-y install make gcc-c ++ kernel-devel m4 ncurses-devel openssl-devel java-devel unixODBC-devel;
Erlang installation Method 1: Source code compilation

Visit the official website download page

Wget http://www.erlang.org/download/otp_src_R16B03.tar.gz;tar-zxvf otp_src_R16B03.tar.gz; cd otp_src_R16B03 ;. /configure -- prefix =/usr/local/erlang -- with-ssl-enable-threads-enable-smmp-support-enable-kernel-poll -- enable-hipe -- without-javac; # skip java compilation to avoid making & make install;
Configure the erlang environment
# Vi/etc/profile: PATH = $ PATH:/usr/local/erlang/binexport PATH # source/etc/profile
Erlang installation Method 2: YUM installation and installation of erlang YUM source

Visit the official website YUM installation tutorial

# Automatically install erlang's YUM source wget http://packages.erlang-solutions.com/erlang-solutions-1.0-1.noarch.rpmrpm-Uvh erlang-solutions-1.0-1.noarch.rpm # or manually install YUM source rpm -- import http://packages.erlang-solutions.com/rpm/erlang_solutions.ascAdd the following lines to some file in/etc/yum. repos. d/: [erlang-solutions] name = Centos $ releasever-$ basearch-Erlang Solutionsbaseurl = Optional
Yum erlang
yum -y install erlang;
Installation successful detection

After the installation is complete, enter "erl" and the following prompt indicates that the installation is successful:

[root@localhost ~]# erlErlang/OTP 18 [erts-7.2] [source-e6dd627] [64-bit] [async-threads:10] [hipe] [kernel-poll:false]Eshell V7.2  (abort with ^G)

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.