Install amqp extension and subscribe to/publish Demo (PHP version) (5), amqpdemo

Source: Internet
Author: User
Tags rabbitmq

Install amqp extension and subscribe to/publish Demo (PHP version) (5), amqpdemo

This article describes how to use RabbitMQ in PHP to subscribe to and publish messages. My system is still Centos7. For convenience, I use Docker to deploy the application server. The Container environment is centos7 + nginx + php5.6.

Run the environment and install AMQP extension:

I won't talk about how to install Docker. Many tutorials on the Internet are very simple. If there is a ready-made php environment, you can use it directly. The image I used in Docker is named webdevops/php-nginx and the tag is: centos-7-php56. Download image:
(The international bandwidth egress is unstable and may fail to be downloaded. You can repeat it once)

Docker pull webdevops/php-nginx: centos-7-php56 // download image docker run-d-p 80: 80 -- name rabbitmq webdevops/php-nginx: centos-7-php56 // run the container docker exec-ti rabbitmq/bin/bash // enter the container

After entering the container, check whether the environment has corresponding extensions

cd appvi index.php    
 

We just used port 80 when running the container and entered http: // ip in the browser

No amqp-related information is found. Install the amqp extension.

yum install gcc librabbitmq-devel.x86_64 php56w-devel -ywget http://pecl.php.net/get/amqp-1.4.0.tgztar -zxvf amqp-1.4.0.tgzcd amqp-1.4.0phpize./configure --with-amqpmake && make install

Enable extension = amqp. so in php. ini and restart the php-fpm or Web server.

vi /etc/php.ini    extension=amqp.so

I will restart the container directly here. If the host machine directly installs the php environment, it will restart the environment directly.

Exit // exit the container docker restart rabbitmq // restart the container

Check phpinfo again. The amqp extension has been installed:

Publish a message in publish

Create a publish. php file in the/app path.

touch publish.phpvi publish.php

The following is the PHP code. We first define the switch, queue, RoutingKey, message, and other variables used for sending messages.

$queueName = 'superrd';$exchangeName = 'superrd';$routeKey = 'superrd';$message = 'Hello World!';

Establish a connection as described in Chapter 2.

$connection = new AMQPConnection(array('host' => '10.99.121.137', 'port' => '5672', 'vhost' => '/', 'login' => 'superrd', 'password' => 'superrd'));$connection->connect() or die("Cannot connect to the broker!\n");

Create a channel.

$channel = new AMQPChannel($connection);

Create a new Switch Exchange and define the properties. Chapter 2 describes four types of switches. DIRECT Connection is used here. AMQP_DURABLE indicates that this is a persistent switch and will not be lost due to server exceptions or other factors.

$exchange = new AMQPExchange($channel);$exchange->setName($exchangeName);$exchange->setType(AMQP_EX_TYPE_DIRECT);$exchange->setFlags(AMQP_DURABLE);$exchange->declareExchange();

Create a Queue. As mentioned earlier, the producer sends messages to Exchange, and Exchange delivers the messages to the Queue based on the binding relationship, that is, if the producer does not have a queue bound to it when producing messages, the messages will be lost. To ensure the system is more robust, Exchange and Queue are created for both the message producer and consumer, and the attributes are not changed after the message is created. Similarly, AMQP_DURABLE indicates that this is a persistent queue, and the queue will be written to the disk. It should be noted that, although messages are cached in the queue, messages in the queue are not persistent or persistent. Message persistence needs to be set separately.

$queue = new AMQPQueue($channel);$queue->setName($queueName);$queue->setFlags(AMQP_DURABLE);$queue->declareQueue();

Use routeKey to bind a vswitch and a queue.

$queue->bind($exchangeName, $routeKey);

Now, you can send the message below.

$exchange->publish($message,$routeKey);

If you want messages to be persistent, you can use the following code. The actual test results will double the performance of messages published after messages are persisted. My disk is a pcie SSD, if you use a mechanical disk, the performance reduction is estimated to be more obvious. In the case of 24-core CPU, 48 gb memory, pcie SSD, and single thread, about 25 thousand non-persistent messages can be published per second, after persistence, it becomes about 12 thousand.

$exchange->publish($message,$routeKey,AMQP_NOPARAM, array('delivery_mode'=>2));

Disconnect.

$connection->disconnect();

After publishing a message, you can use a WEB tool to check whether the message is successfully published,
Check that the vswitch has an additional superid switch.

Check that the vswitch has a superrd queue.

Click queue to view queue details. The Bindings label shows the binding relationship between the vswitch and the queue.

Click Get message (s) to view the message in the queue.

This indicates that a message has been published to the message queue. The complete PHP code is as follows.

 '10. 99.121.20.', 'Port' => '123', 'vhost' => '/', 'login' => 'superrd ', 'Password' => 'superrd'); $ connection-> connect () or die ("Cannot connect to the broker! \ N "); try {$ channel = new AMQPChannel ($ connection); $ exchange = new AMQPExchange ($ channel); $ exchange-> setName ($ exchangeName ); $ exchange-> setType (AMQP_EX_TYPE_DIRECT); $ exchange-> setFlags (AMQP_DURABLE); $ exchange-> declareExchange (); $ queue = new AMQPQueue ($ channel ); $ queue-> setName ($ queueName); $ queue-> setFlags (AMQP_DURABLE); $ queue-> declareQueue (); $ queue-> bind ($ exchangeName, $ routeKey ); $ exchange -> Publish ($ message, $ routeKey); var_dump ("[x] Sent 'Hello World! '");} Catch (AMQPConnectionException $ e) {var_dump ($ e); exit () ;}$ connection-> disconnect ();
Subscribe to messages

Create a subscribe. php file in the/app path.

touch subscribe.phpvi subscribe.php

The following is the PHP code. Like publishing a message, we first define variables such as vswitches, queues, and RoutingKey.

$queueName = 'superrd';$exchangeName = 'superrd';$routeKey = 'superrd';

Establish a connection as described in Chapter 2.

$connection = new AMQPConnection(array('host' => '10.99.121.137', 'port' => '5672', 'vhost' => '/', 'login' => 'superrd', 'password' => 'superrd'));$connection->connect() or die("Cannot connect to the broker!\n");

Create a channel.

$channel = new AMQPChannel($connection);

Create a vswitch like publishing a message.

$exchange = new AMQPExchange($channel);$exchange->setName($exchangeName);$exchange->setType(AMQP_EX_TYPE_DIRECT);$exchange->setFlags(AMQP_DURABLE);$exchange->declareExchange();

Create a Queue.

$queue = new AMQPQueue($channel);$queue->setName($queueName);$queue->setFlags(AMQP_DURABLE);$queue->declareQueue();

Use routeKey to bind a vswitch and a queue.

$queue->bind($exchangeName, $routeKey);

The point is to block the subscription of messages.

// Echo "Message: \ n" in blocking mode; while (True) {$ queue-> consume ('processmessage '); // automatic ACK response // $ queue-> consume ('processmessage', AMQP_AUTOACK);} $ conn-> disconnect (); /** consumption callback function * processes messages */function processMessage ($ envelope, $ q) {$ msg = $ envelope-> getBody (); echo $ msg. "\ n"; // process the message $ q-> ack ($ envelope-> getDeliveryTag (); // manually send ACK response}

Note that the listener is blocked and cannot be accessed by the browser due to the output buffer. Use scripts for access.

php /app/subscribe.php

View queues using WEB tools. The number of messages in the superrd queue is already 0.

The complete PHP code is as follows.

 '10. 99.121.20.', 'Port' => '123', 'vhost' => '/', 'login' => 'superrd ', 'Password' => 'superrd'); $ connection-> connect () or die ("Cannot connect to the broker! \ N "); $ channel = new AMQPChannel ($ connection); $ exchange = new AMQPExchange ($ channel); $ exchange-> setName ($ exchangeName ); $ exchange-> setType (AMQP_EX_TYPE_DIRECT); $ exchange-> setFlags (AMQP_DURABLE); $ exchange-> declareExchange (); $ queue = new AMQPQueue ($ channel ); $ queue-> setName ($ queueName); $ queue-> setFlags (AMQP_DURABLE); $ queue-> declareQueue (); $ queue-> bind ($ exchangeName, $ routeKey ); // echo "Message: \ n" in blocking mode; while (True) {$ queue-> consume ('processmessage '); // automatic ACK response // $ queue-> consume ('processmessage', AMQP_AUTOACK);} $ conn-> disconnect (); /** consumption callback function * processes messages */function processMessage ($ envelope, $ q) {$ msg = $ envelope-> getBody (); echo $ msg. "\ n"; // process the message $ q-> ack ($ envelope-> getDeliveryTag (); // manually send ACK response}

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.