【消息队列】RabbitMQ+PHP实现

本文链接:http://www.cnblogs.com/aiweixiao/p/7374249.html

文档提纲:

 

扫描关注微信公众号

 

 

1.【下载和安装】

  1)gitHub下载地址: https://github.com/php-amqplib/php-amqplib

  2)【环境准备】:

         安装php的RabbitMQ PHP扩展安装,依赖的Erlang环境

   参考文档: http://www.cnblogs.com/chunguang/p/5634342.html

  3)【类的依赖加载】:建议使用 composer实现,

            composer入门
      4)【教程】:
    官方教程链接地址:http://www.rabbitmq.com/tutorials/tutorial-one-php.html

  5)测试脚本:

            --使用官方的demo:

开一个订阅者窗口
$ cd php-amqplib/demo
$ php amqp_consumer.php



开一个发布者窗口
$ cd php-amqplib/demo
$ php amqp_publisher.php some text to publish

 

 

    --使用第三方脚本 http://blog.csdn.net/u014071426/article/details/53649226

 1 //引用所需文件  
 2 require_once __DIR__ . '/vendor/autoload.php';  
 3 use PhpAmqpLib\Connection\AMQPStreamConnection;  
 4 use PhpAmqpLib\Message\AMQPMessage;  
 5 //建立一个连接通道,声明一个可以发送消息的队列hello  
 6 $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');  
 7 $channel = $connection->channel();  
 8 $channel->queue_declare('hello', false, false, false, false);  
 9   
10 //定义一个消息,消息内容为Hello World!  
11 $msg = new AMQPMessage('Hello World!');  
12 $channel->basic_publish($msg, '', 'hello');  
13   
14 //发送完成后打印消息告诉发布消息的人:发送成功  
15 echo " [x] Sent 'Hello World!'\n";  
16 //关闭连接  
17 $channel->close();  
18 $connection->close();
View Code
 1     require_once __DIR__ . '/vendor/autoload.php';  
 2     use PhpAmqpLib\Connection\AMQPStreamConnection;  
 3     $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');  
 4     $channel = $connection->channel();  
 5       
 6     $channel->queue_declare('hello', false, false, false, false);  
 7       
 8     echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";  
 9     $callback = function($msg) {  
10       echo " [x] Received ", $msg->body, "\n";  
11     };  
12       
13     //在接收消息的时候调用$callback函数  
14     $channel->basic_consume('hello', '', false, true, false, false, $callback);  
15       
16     while(count($channel->callbacks)) {  
17         $channel->wait();  
18     }  

 

posted @ 2017-08-26 09:19  程序员的文娱情怀  阅读(12805)  评论(2编辑  收藏  举报