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 相关文章推荐
随时给自己贴的图片加文字的php代码
Mar 08 PHP
php strlen mb_strlen计算中英文混排字符串长度
Jul 10 PHP
PHP 显示客户端IP与服务器IP的代码
Oct 12 PHP
PHP中删除变量时unset()和null的区别分析
Jan 27 PHP
php连接数据库代码应用分析
May 29 PHP
对象失去焦点时自己动提交数据的实现代码
Nov 06 PHP
PHP实现绘制3D扇形统计图及图片缩放实例
Oct 01 PHP
PHP永久登录、记住我功能实现方法和安全做法
Apr 27 PHP
PHP使用pear自带的mail类库发邮件的方法
Jul 08 PHP
php解析url并得到url中的参数及获取url参数的四种方式
Oct 26 PHP
Laravel如何实现自动加载类
Oct 14 PHP
一文搞懂php的垃圾回收机制
Jun 18 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
yii去掉必填项中星号的方法
2015/12/28 PHP
php简单实现单态设计模式的方法分析
2017/07/28 PHP
一个js封装的不错的选项卡效果代码
2008/02/15 Javascript
checkbox 复选框不能为空
2009/07/11 Javascript
也说JavaScript中String类的replace函数
2011/09/22 Javascript
javascript 禁用IE工具栏,导航栏等等实现代码
2013/04/01 Javascript
JS实现定时自动关闭DIV层提示框的方法
2015/05/11 Javascript
函数window.open实现关闭所有的子窗口
2015/08/03 Javascript
jquery.validate使用详解
2016/06/02 Javascript
Javascript 引擎工作机制详解
2016/11/30 Javascript
js canvas实现适用于移动端的百分比仪表盘dashboard
2017/07/18 Javascript
浅谈angular2路由预加载策略
2017/10/04 Javascript
详解redis在nodejs中的应用
2018/05/02 NodeJs
echarts整合多个类似option的方法实例
2018/07/10 Javascript
跨域解决之JSONP和CORS的详细介绍
2018/11/21 Javascript
javascript中的数据类型检测方法详解
2019/08/07 Javascript
NodeJS http模块用法示例【创建web服务器/客户端】
2019/11/05 NodeJs
vue 关闭浏览器窗口的时候,清空localStorage的数据示例
2019/11/06 Javascript
JS变量提升及函数提升实例解析
2020/09/03 Javascript
angular *Ngif else用法详解
2020/12/15 Javascript
Python THREADING模块中的JOIN()方法深入理解
2015/02/18 Python
python删除列表中重复记录的方法
2015/04/28 Python
Python实现的简单算术游戏实例
2015/05/26 Python
基于进程内通讯的python聊天室实现方法
2015/06/28 Python
详解Python编程中包的概念与管理
2015/10/16 Python
一步步解析Python斗牛游戏的概率
2016/02/12 Python
Django如何自定义分页
2018/09/25 Python
python3文件复制、延迟文件复制任务的实现方法
2019/09/02 Python
BookOutlet加拿大:在网上书店购买廉价折扣图书和小说
2018/10/05 全球购物
园林设计师自荐信
2013/11/18 职场文书
思想汇报格式
2014/01/05 职场文书
银行竞聘演讲稿
2014/05/16 职场文书
美术教师个人总结
2015/02/06 职场文书
厉行节约工作总结
2015/08/12 职场文书
我对PyTorch dataloader里的shuffle=True的理解
2021/05/20 Python
Pygame Event事件模块的详细示例
2021/11/17 Python