RabbitMQ php 使用

RabbitMQ是一个开源的基于AMQP(Advanced Message Queuing Protocol)标准,并且可靠性高的企业级消息系统,目前很多网站在用,包括reddit,Poppen.de等。

Java代码  收藏代码
  1. 1. 安装RabbitMQ  
  2. sudo apt-get install rabbitmq-server  
  3. sudo /etc/init.d/rabbitmq-server start  
Java代码  收藏代码
  1. 2. 安装librabbitmq  
  2. sudo apt-get install mercurial  
  3. hg clone http://hg.rabbitmq.com/rabbitmq-c  
  4. cd rabbitmq-c  
  5. hg clone http://hg.rabbitmq.com/rabbitmq-codegen codegen  
  6. autoreconf -i && ./configure && make && sudo make install  
  7.   
  8. 3. 安装php-rabbit扩展  
  9. wget http://php-rabbit.googlecode.com/files/php-rabbit.r91.tar.gz  
  10. tar -zxvf php-rabbit.r91.tar.gz  
  11. cd php-rabbit.r91  
  12. /path/to/php/bin/phpize  
  13. ./configure –with-amqp –with-php-config=/path/to/php/bin/php-config  
  14. make && sudo make install  
  15. 编辑 php.ini 添加:  
  16. extension=rabbit.so  
  17. 输出phpinfo看下是否扩展已经加载成功,have fun:)  
Php代码  收藏代码
  1. <?php  
  2. /** 
  3.  * producer demo 
  4.  * 
  5.  * @author wei 
  6.  * @version $Id$ 
  7.  **/  
  8. $params = array('host' =>'localhost',  
  9.                 'port' => 5672,  
  10.                 'login' => 'guest',  
  11.                 'password' => 'guest',  
  12.                 'vhost' => '/');  
  13. $cnn = new AMQPConnect($params);  
  14.    
  15. // declare Exchange  
  16. $exchange = new AMQPExchange($cnn);  
  17. $exchange->declare('ex1''topic', AMQP_DURABLE );  
  18.    
  19. // declare Queue  
  20. $queue = new AMQPQueue($cnn);    
  21. $queue->declare('queue1', AMQP_DURABLE);   
  22.    
  23. // bind Queue  
  24. $queue->bind('ex1','wei.#');  
  25.    
  26. // publishing  
  27. $msg = "msg";  
  28.    
  29. for ($i=0; $i < 100; $i++) {   
  30.     $res = $exchange->publish($i . 'msg''wei.' . $i);  
  31.     if ($res) {  
  32.         echo $i . 'msg' . " Yes ";  
  33.     } else {  
  34.         echo $i . 'msg' . " No ";  
  35.     }  
  36. }  
  37.    
  38. ?>  
  39.   
  40. consumer:  
  41. ?View Code PHP  
  42.   
  43. <?php  
  44. /** 
  45.  * consumer demo 
  46.  * 
  47.  * @author wei 
  48.  * @version $Id$ 
  49.  **/  
  50. $params = array('host' =>'localhost',  
  51.                 'port' => 5672,  
  52.                 'login' => 'guest',  
  53.                 'password' => 'guest',  
  54.                 'vhost' => '/');  
  55. $cnn = new AMQPConnect($params);  
  56.    
  57. // create the Queue  
  58. $queue = new AMQPQueue($cnn'queue1');  
  59. $queueMessages = $queue->consume(100);  
  60.    
  61. foreach($queueMessages as $item) {  
  62.     echo "$i.$item ";  
  63. }  
  64. ?>  
原文地址:https://www.cnblogs.com/cnsanshao/p/3463899.html