PHP基于rabbitmq操作类的生产者和消费者功能示例


Posted in PHP onJune 16, 2018

本文实例讲述了PHP基于rabbitmq操作类的生产者和消费者功能。分享给大家供大家参考,具体如下:

注意事项:

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

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

RabbitMQCommand.php操作类代码

<?php
/*
 * amqp协议操作类,可以访问rabbitMQ
 * 需先安装php_amqp扩展
 */
class RabbitMQCommand{
  public $configs = array();
  //交换机名称
  public $exchange_name = '';
  //队列名称
  public $queue_name = '';
  //路由名称
  public $route_key = '';
  /*
   * 持久化,默认True
   */
  public $durable = True;
  /*
   * 自动删除
   * exchange is deleted when all queues have finished using it
   * queue is deleted when last consumer unsubscribes
   *
   */
  public $autodelete = False;
  /*
   * 镜像
   * 镜像队列,打开后消息会在节点之间复制,有master和slave的概念
   */
  public $mirror = False;
  private $_conn = Null;
  private $_exchange = Null;
  private $_channel = Null;
  private $_queue = Null;
  /*
   * @configs array('host'=>$host,'port'=>5672,'username'=>$username,'password'=>$password,'vhost'=>'/')
   */
  public function __construct($configs = array(), $exchange_name = '', $queue_name = '', $route_key = '') {
    $this->setConfigs($configs);
    $this->exchange_name = $exchange_name;
    $this->queue_name = $queue_name;
    $this->route_key = $route_key;
  }
  private function setConfigs($configs) {
    if (!is_array($configs)) {
      throw new Exception('configs is not array');
    }
    if (!($configs['host'] && $configs['port'] && $configs['username'] && $configs['password'])) {
      throw new Exception('configs is empty');
    }
    if (empty($configs['vhost'])) {
      $configs['vhost'] = '/';
    }
    $configs['login'] = $configs['username'];
    unset($configs['username']);
    $this->configs = $configs;
  }
  /*
   * 设置是否持久化,默认为True
   */
  public function setDurable($durable) {
    $this->durable = $durable;
  }
  /*
   * 设置是否自动删除
   */
  public function setAutoDelete($autodelete) {
    $this->autodelete = $autodelete;
  }
  /*
   * 设置是否镜像
   */
  public function setMirror($mirror) {
    $this->mirror = $mirror;
  }
  /*
   * 打开amqp连接
   */
  private function open() {
    if (!$this->_conn) {
      try {
        $this->_conn = new AMQPConnection($this->configs);
        $this->_conn->connect();
        $this->initConnection();
      } catch (AMQPConnectionException $ex) {
        throw new Exception('cannot connection rabbitmq',500);
      }
    }
  }
  /*
   * rabbitmq连接不变
   * 重置交换机,队列,路由等配置
   */
  public function reset($exchange_name, $queue_name, $route_key) {
    $this->exchange_name = $exchange_name;
    $this->queue_name = $queue_name;
    $this->route_key = $route_key;
    $this->initConnection();
  }
  /*
   * 初始化rabbit连接的相关配置
   */
  private function initConnection() {
    if (empty($this->exchange_name) || empty($this->queue_name) || empty($this->route_key)) {
      throw new Exception('rabbitmq exchange_name or queue_name or route_key is empty',500);
    }
    $this->_channel = new AMQPChannel($this->_conn);
    $this->_exchange = new AMQPExchange($this->_channel);
    $this->_exchange->setName($this->exchange_name);
    $this->_exchange->setType(AMQP_EX_TYPE_DIRECT);
    if ($this->durable)
      $this->_exchange->setFlags(AMQP_DURABLE);
    if ($this->autodelete)
      $this->_exchange->setFlags(AMQP_AUTODELETE);
    $this->_exchange->declare();
    $this->_queue = new AMQPQueue($this->_channel);
    $this->_queue->setName($this->queue_name);
    if ($this->durable)
      $this->_queue->setFlags(AMQP_DURABLE);
    if ($this->autodelete)
      $this->_queue->setFlags(AMQP_AUTODELETE);
    if ($this->mirror)
      $this->_queue->setArgument('x-ha-policy', 'all');
    $this->_queue->declare();
    $this->_queue->bind($this->exchange_name, $this->route_key);
  }
  public function close() {
    if ($this->_conn) {
      $this->_conn->disconnect();
    }
  }
  public function __sleep() {
    $this->close();
    return array_keys(get_object_vars($this));
  }
  public function __destruct() {
    $this->close();
  }
  /*
   * 生产者发送消息
   */
  public function send($msg) {
    $this->open();
    if(is_array($msg)){
      $msg = json_encode($msg);
    }else{
      $msg = trim(strval($msg));
    }
    return $this->_exchange->publish($msg, $this->route_key);
  }
  /*
   * 消费者
   * $fun_name = array($classobj,$function) or function name string
   * $autoack 是否自动应答
   *
   * function processMessage($envelope, $queue) {
      $msg = $envelope->getBody();
      echo $msg."\n"; //处理消息
      $queue->ack($envelope->getDeliveryTag());//手动应答
    }
   */
  public function run($fun_name, $autoack = True){
    $this->open();
    if (!$fun_name || !$this->_queue) return False;
    while(True){
      if ($autoack) $this->_queue->consume($fun_name, AMQP_AUTOACK);
      else $this->_queue->consume($fun_name);
    }
  }
}

send.php生产者代码

<?php
set_time_limit(0);
include_once('RabbitMQCommand.php');
$configs = array('host'=>'127.0.0.1','port'=>5672,'username'=>'asdf','password'=>'123456','vhost'=>'/');
$exchange_name = 'class-e-1';
$queue_name = 'class-q-1';
$route_key = 'class-r-1';
$ra = new RabbitMQCommand($configs,$exchange_name,$queue_name,$route_key);
for($i=0;$i<=100;$i++){
  $ra->send(date('Y-m-d H:i:s',time()));
}
exit();

accept.php消费者代码

<?php
error_reporting(0);
include_once('RabbitMQCommand.php');
$configs = array('host'=>'127.0.0.1','port'=>5672,'username'=>'asdf','password'=>'123456','vhost'=>'/');
$exchange_name = 'class-e-1';
$queue_name = 'class-q-1';
$route_key = 'class-r-1';
$ra = new RabbitMQCommand($configs,$exchange_name,$queue_name,$route_key);
class A{
  function processMessage($envelope, $queue) {
    $msg = $envelope->getBody();
    $envelopeID = $envelope->getDeliveryTag();
    $pid = posix_getpid();
    file_put_contents("log{$pid}.log", $msg.'|'.$envelopeID.''."\r\n",FILE_APPEND);
    $queue->ack($envelopeID);
  }
}
$a = new A();
$s = $ra->run(array($a,'processMessage'),false);

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
frename PHP 灵活文件命名函数 frename
Sep 09 PHP
php实现文件下载更能介绍
Nov 23 PHP
PHP使用GIFEncoder类生成gif动态滚动字幕
Jul 01 PHP
PHP面向对象详解(三)
Dec 07 PHP
基于laravel制作APP接口(API)
Mar 15 PHP
PHP判断JSON对象是否存在的方法(推荐)
Jul 06 PHP
PHPWind9.0手动屏蔽验证码解决后台关闭验证码但是依然显示的问题
Aug 12 PHP
PHP利用超级全局变量$_GET来接收表单数据的实例
Nov 05 PHP
php 可变函数使用小结
Jun 12 PHP
Laravel框架文件上传功能实现方法示例
Apr 16 PHP
PHP反射原理与用法深入分析
Sep 28 PHP
在 Laravel 6 中缓存数据库查询结果的方法
Dec 11 PHP
PHP7.1实现的AES与RSA加密操作示例
Jun 15 #PHP
PHP观察者模式示例【Laravel框架中有用到】
Jun 15 #PHP
PHP堆栈调试操作简单示例
Jun 15 #PHP
在Laravel5.6中使用Swoole的协程数据库查询
Jun 15 #PHP
ThinkPHP框架实现的邮箱激活功能示例
Jun 15 #PHP
基于swoole实现多人聊天室
Jun 14 #PHP
PHP实现数组转JSon和JSon转数组的方法示例
Jun 14 #PHP
You might like
用来解析.htgroup文件的PHP类
2012/09/05 PHP
PHP配置把错误日志以邮件方式发送方法(Windows系统)
2015/06/23 PHP
PHP实现的XML操作类【XML Library】
2016/12/29 PHP
thinkphp 验证码 的使用小结
2017/05/07 PHP
Laravel框架中自定义模板指令总结
2017/12/17 PHP
PHP实现将base64编码字符串转换成图片示例
2018/06/22 PHP
javascript 伪数组实现方法
2010/10/11 Javascript
Js四则运算函数代码
2012/07/21 Javascript
js arguments对象应用介绍
2012/11/28 Javascript
纯js实现瀑布流展现照片(自动适应窗口大小)
2013/04/08 Javascript
基于MVC3方式实现下拉列表联动(JQuery)
2013/09/02 Javascript
js中switch case循环实例代码
2013/12/30 Javascript
json中换行符的处理方法示例介绍
2014/06/10 Javascript
与Math.pow 相反的函数使用介绍
2014/08/04 Javascript
JavaScript中判断页面关闭、页面刷新的实现代码
2014/08/27 Javascript
JavaScript 数组- Array的方法总结(推荐)
2016/07/21 Javascript
再谈javascript常见错误及解决方法
2016/09/16 Javascript
jQuery DateTimePicker 日期和时间插件示例
2017/01/22 Javascript
详解webpack 配合babel 将es6转成es5 超简单实例
2017/05/02 Javascript
利用jsonp解决js读取本地json跨域的问题
2018/12/11 Javascript
[08:42]DOTA2每周TOP10 精彩击杀集锦vol.2
2014/06/25 DOTA
python使用urllib2提交http post请求的方法
2015/05/26 Python
python实现的系统实用log类实例
2015/06/30 Python
Python实现利用163邮箱远程关电脑脚本
2018/02/22 Python
python实现m3u8格式转换为mp4视频格式
2018/02/28 Python
python plotly绘制直方图实例详解
2019/07/22 Python
python3.x 生成3维随机数组实例
2019/11/28 Python
Django中的session用法详解
2020/03/09 Python
利用python+request通过接口实现人员通行记录上传功能
2021/01/13 Python
斯德哥尔摩通票:Stockholm Pass
2018/01/09 全球购物
德国拖鞋网站:German Slippers
2019/11/08 全球购物
幼儿园母亲节活动方案
2014/03/10 职场文书
卫生巾广告词
2014/03/18 职场文书
长城英文导游词
2015/01/30 职场文书
导师鉴定意见
2015/06/05 职场文书
运动会主持词大全
2015/07/02 职场文书