php rabbitmq操作类及生产者和消费者实例代码

注意事项:

1、accept.php消费者代码需要在命令行执行

2、'username'=>'asdf','password'=>'123456' 改成自己的帐号和密码


RabbitMQCommand.php操作类代码

[php]  view plain  copy
  1. <?php  
  2. /* 
  3.  * amqp协议操作类,可以访问rabbitMQ 
  4.  * 需先安装php_amqp扩展 
  5.  */  
  6. class RabbitMQCommand{  
  7.   
  8.     public $configs = array();  
  9.     //交换机名称  
  10.     public $exchange_name = '';  
  11.     //队列名称  
  12.     public $queue_name = '';  
  13.     //路由名称  
  14.     public $route_key = '';  
  15.     /* 
  16.      * 持久化,默认True 
  17.      */  
  18.     public $durable = True;  
  19.     /* 
  20.      * 自动删除 
  21.      * exchange is deleted when all queues have finished using it 
  22.      * queue is deleted when last consumer unsubscribes 
  23.      *  
  24.      */  
  25.     public $autodelete = False;  
  26.     /* 
  27.      * 镜像 
  28.      * 镜像队列,打开后消息会在节点之间复制,有master和slave的概念 
  29.      */  
  30.     public $mirror = False;  
  31.       
  32.     private $_conn = Null;  
  33.     private $_exchange = Null;  
  34.     private $_channel = Null;  
  35.     private $_queue = Null;  
  36.   
  37.     /* 
  38.      * @configs array('host'=>$host,'port'=>5672,'username'=>$username,'password'=>$password,'vhost'=>'/') 
  39.      */  
  40.   
  41.     public function __construct($configs = array(), $exchange_name = ''$queue_name = ''$route_key = '') {  
  42.         $this->setConfigs($configs);  
  43.         $this->exchange_name = $exchange_name;  
  44.         $this->queue_name = $queue_name;  
  45.         $this->route_key = $route_key;  
  46.     }  
  47.       
  48.     private function setConfigs($configs) {  
  49.         if (!is_array($configs)) {  
  50.             throw new Exception('configs is not array');  
  51.         }  
  52.         if (!($configs['host'] && $configs['port'] && $configs['username'] && $configs['password'])) {  
  53.             throw new Exception('configs is empty');  
  54.         }  
  55.         if (empty($configs['vhost'])) {  
  56.             $configs['vhost'] = '/';  
  57.         }  
  58.         $configs['login'] = $configs['username'];  
  59.         unset($configs['username']);  
  60.         $this->configs = $configs;  
  61.     }  
  62.   
  63.     /* 
  64.      * 设置是否持久化,默认为True 
  65.      */  
  66.   
  67.     public function setDurable($durable) {  
  68.         $this->durable = $durable;  
  69.     }  
  70.   
  71.     /* 
  72.      * 设置是否自动删除 
  73.      */  
  74.   
  75.     public function setAutoDelete($autodelete) {  
  76.         $this->autodelete = $autodelete;  
  77.     }  
  78.     /* 
  79.      * 设置是否镜像 
  80.      */  
  81.     public function setMirror($mirror) {  
  82.         $this->mirror = $mirror;  
  83.     }  
  84.   
  85.     /* 
  86.      * 打开amqp连接 
  87.      */  
  88.   
  89.     private function open() {  
  90.         if (!$this->_conn) {  
  91.             try {  
  92.                 $this->_conn = new AMQPConnection($this->configs);  
  93.                 $this->_conn->connect();  
  94.                 $this->initConnection();  
  95.             } catch (AMQPConnectionException $ex) {  
  96.                 throw new Exception('cannot connection rabbitmq',500);  
  97.             }  
  98.         }  
  99.     }  
  100.   
  101.     /* 
  102.      * rabbitmq连接不变 
  103.      * 重置交换机,队列,路由等配置 
  104.      */  
  105.   
  106.     public function reset($exchange_name$queue_name$route_key) {  
  107.         $this->exchange_name = $exchange_name;  
  108.         $this->queue_name = $queue_name;  
  109.         $this->route_key = $route_key;  
  110.         $this->initConnection();  
  111.     }  
  112.   
  113.     /* 
  114.      * 初始化rabbit连接的相关配置 
  115.      */  
  116.   
  117.     private function initConnection() {  
  118.         if (empty($this->exchange_name) || empty($this->queue_name) || empty($this->route_key)) {  
  119.             throw new Exception('rabbitmq exchange_name or queue_name or route_key is empty',500);  
  120.         }  
  121.         $this->_channel = new AMQPChannel($this->_conn);  
  122.         $this->_exchange = new AMQPExchange($this->_channel);  
  123.         $this->_exchange->setName($this->exchange_name);  
  124.   
  125.         $this->_exchange->setType(AMQP_EX_TYPE_DIRECT);  
  126.         if ($this->durable)  
  127.             $this->_exchange->setFlags(AMQP_DURABLE);  
  128.         if ($this->autodelete)  
  129.             $this->_exchange->setFlags(AMQP_AUTODELETE);  
  130.         $this->_exchange->declare();  
  131.   
  132.         $this->_queue = new AMQPQueue($this->_channel);  
  133.         $this->_queue->setName($this->queue_name);  
  134.         if ($this->durable)  
  135.             $this->_queue->setFlags(AMQP_DURABLE);  
  136.         if ($this->autodelete)  
  137.             $this->_queue->setFlags(AMQP_AUTODELETE);  
  138.         if ($this->mirror)   
  139.             $this->_queue->setArgument('x-ha-policy''all');  
  140.         $this->_queue->declare();  
  141.           
  142.         $this->_queue->bind($this->exchange_name, $this->route_key);  
  143.     }  
  144.   
  145.     public function close() {  
  146.         if ($this->_conn) {  
  147.             $this->_conn->disconnect();  
  148.         }  
  149.     }  
  150.       
  151.     public function __sleep() {  
  152.         $this->close();  
  153.         return array_keys(get_object_vars($this));  
  154.     }  
  155.   
  156.     public function __destruct() {  
  157.         $this->close();  
  158.     }  
  159.       
  160.     /* 
  161.      * 生产者发送消息 
  162.      */  
  163.     public function send($msg) {  
  164.         $this->open();  
  165.         if(is_array($msg)){  
  166.             $msg = json_encode($msg);  
  167.         }else{  
  168.             $msg = trim(strval($msg));  
  169.         }  
  170.         return $this->_exchange->publish($msg$this->route_key);  
  171.     }  
  172.     /* 
  173.      * 消费者 
  174.      * $fun_name = array($classobj,$function) or function name string 
  175.      * $autoack 是否自动应答 
  176.      *  
  177.      * function processMessage($envelope, $queue) { 
  178.             $msg = $envelope->getBody();  
  179.             echo $msg."\n"; //处理消息 
  180.             $queue->ack($envelope->getDeliveryTag());//手动应答 
  181.         } 
  182.      */  
  183.     public function run($fun_name$autoack = True){  
  184.         $this->open();  
  185.         if (!$fun_name || !$this->_queue) return False;    
  186.         while(True){  
  187.             if ($autoack$this->_queue->consume($fun_name, AMQP_AUTOACK);     
  188.             else $this->_queue->consume($fun_name);      
  189.         }  
  190.     }  
  191.   
  192. }  

send.php生产者代码

[php]  view plain  copy
  1. <?php  
  2. set_time_limit(0);  
  3. include_once('RabbitMQCommand.php');  
  4.   
  5. $configs = array('host'=>'127.0.0.1','port'=>5672,'username'=>'asdf','password'=>'123456','vhost'=>'/');  
  6. $exchange_name = 'class-e-1';  
  7. $queue_name = 'class-q-1';  
  8. $route_key = 'class-r-1';  
  9. $ra = new RabbitMQCommand($configs,$exchange_name,$queue_name,$route_key);  
  10. for($i=0;$i<=100;$i++){  
  11.     $ra->send(date('Y-m-d H:i:s',time()));  
  12. }  
  13. exit();  

accept.php消费者代码

[php]  view plain  copy
  1. <?php  
  2. error_reporting(0);  
  3. include_once('RabbitMQCommand.php');  
  4.   
  5.   
  6. $configs = array('host'=>'127.0.0.1','port'=>5672,'username'=>'asdf','password'=>'123456','vhost'=>'/');  
  7. $exchange_name = 'class-e-1';  
  8. $queue_name = 'class-q-1';  
  9. $route_key = 'class-r-1';  
  10. $ra = new RabbitMQCommand($configs,$exchange_name,$queue_name,$route_key);  
  11.   
  12.   
  13. class A{  
  14.     function processMessage($envelope$queue) {  
  15.         $msg = $envelope->getBody();  
  16.         $envelopeID = $envelope->getDeliveryTag();  
  17.         $pid = posix_getpid();  
  18.         file_put_contents("log{$pid}.log"$msg.'|'.$envelopeID.''."\r\n",FILE_APPEND);  
  19.         $queue->ack($envelopeID);  
  20.     }  
  21. }  
  22. $a = new A();  
  23.   
  24.   
  25. $s = $ra->run(array($a,'processMessage'),false);  

猜你喜欢

转载自blog.csdn.net/zhaanghao/article/details/78892589