基于PHP使用rabbitmq实现消息队列

1.从github上面获取AMQP基于php的实现扩展

2.创建生产者 send.php

 1 require(__DIR__ . '/../protected/vendor/autoload.php');
 2 
 3 use PhpAmqpLib\Connection\AMQPStreamConnection;
 4 use PhpAmqpLib\Message\AMQPMessage;
 5 
 6 
 7 $connection = new AMQPStreamConnection('192.168.38.129', 5672, 'fanwq', 'ysq');
 8 $channel = $connection->channel();
 9 $channel->queue_declare('hello', false, false, false, false);
10 
11 $msg = new AMQPMessage($i.'-Hello World! --' . $_SERVER['SSH_CONNECTION']);
12 $channel->basic_publish($msg, '', 'hello');
13 echo " [{$i}] Sent 'Hello World!'\n";
14 $channel->close();
15 $connection->close();
View Code

3.创建消费者 receive.php

 1 require(__DIR__ . '/../protected/vendor/autoload.php');
 2 
 3 use PhpAmqpLib\Connection\AMQPStreamConnection;
 4 use PhpAmqpLib\Message\AMQPMessage;
 5 
 6 $connection = new AMQPStreamConnection('192.168.38.129', 5672, 'fanwq', 'ysq');
 7 $channel = $connection->channel();
 8 
 9 $channel->queue_declare('hello', false, false, false, false);
10 echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";
11 $callback = function($msg) {
12     echo " [x] Received ", $msg->body, "\n";
13 };
14 
15 $channel->basic_consume('hello', '', false, true, false, false, $callback);
16 
17 while(count($channel->callbacks)) {
18     $channel->wait();
19 }
View Code

4.在cli模式下 分别执行 send.php  receive.php 可以看到如下:

说明生产 消费端均ok。

 

5.管理 查看队列消息:安装rabbitmq_management插件

【5-1】查看当前可用插件:

 

【5-2】 安装启用 rabbitmq_management插件

【5-3】进入rabbitmq_management管理端:http://192.168.38.129:15672/

【5-4】 guest用户没有权限 需要授权

rabbitmqctl set_user_tags guest monitoring 

rabbitmqctl set_user_tags guest management

 

【5-5】登陆成功

 

posted @ 2016-11-28 18:05  justphp  阅读(4289)  评论(0编辑  收藏  举报