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中date()日期函数有关参数整理
Jul 19 PHP
php网上商城购物车设计代码分享
Feb 15 PHP
简单的方法让你的后台登录更加安全(php中加session验证)
Aug 22 PHP
php检查是否是ajax请求的方法
Apr 16 PHP
php $_SESSION会员登录实例分享
Jan 19 PHP
PHP读取大文件的多种方法介绍
Apr 04 PHP
PHP实现基于mysqli的Model基类完整实例
Apr 08 PHP
php微信开发之百度天气预报
Nov 18 PHP
Zend Framework常用校验器详解
Dec 09 PHP
PHP简单获取随机数的常用方法小结
Jun 07 PHP
Yii 2.0自带的验证码使用经验分享
Jun 19 PHP
laravel框架中间件简单使用方法示例
Jan 25 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
php为什么选mysql作为数据库? Mysql 创建用户方法
2007/07/02 PHP
PHP daddslashes 使用方法介绍
2012/10/26 PHP
javascript+php实现根据用户时区显示当地时间的方法
2015/03/11 PHP
php中执行系统命令的方法
2015/03/21 PHP
yii框架redis结合php实现秒杀效果(实例代码)
2017/10/26 PHP
js检测客户端不是firefox则提示下载
2007/04/07 Javascript
jQuery 相关控件的事件操作分解
2009/08/03 Javascript
js字符串转成JSON
2013/11/07 Javascript
js控制淡入淡出示例代码
2013/11/12 Javascript
jQuery实现冻结表头的方法
2015/03/09 Javascript
简介AngularJS的视图功能应用
2015/06/17 Javascript
angularjs客户端实现压缩图片文件并上传实例
2015/07/06 Javascript
给before和after伪元素设置js效果的方法
2015/12/04 Javascript
探寻JavaScript中this指针指向
2016/04/23 Javascript
Javascript设计模式之装饰者模式详解篇
2017/01/17 Javascript
NodeJs模拟登陆正方教务
2017/04/28 NodeJs
Node.js 实现简单的接口服务器的实例代码
2017/05/23 Javascript
jQuery实现每隔一段时间自动更换样式的方法分析
2018/05/03 jQuery
angularJs中跳转到指定的锚点实例($anchorScroll)
2018/08/31 Javascript
[02:18]《我与DAC》之工作人员:为了热爱DOTA2的玩家们
2018/03/28 DOTA
利用python批量给云主机配置安全组的方法教程
2017/06/21 Python
tensorflow输出权重值和偏差的方法
2018/02/10 Python
详解python 3.6 安装json 模块(simplejson)
2019/04/02 Python
python中删除某个元素的方法解析
2019/11/05 Python
python词云库wordCloud使用方法详解(解决中文乱码)
2020/02/17 Python
如何在python中执行另一个py文件
2020/04/30 Python
Python使用Opencv实现边缘检测以及轮廓检测的实现
2020/12/31 Python
优衣库美国官网:UNIQLO美国
2018/04/14 全球购物
巴西儿童时尚购物网站:Dinda
2019/08/14 全球购物
介绍一下SQL注入攻击的种类和防范手段
2012/02/18 面试题
办公文员的工作岗位职责
2013/11/12 职场文书
幼儿园小班教师寄语
2014/04/03 职场文书
超市周年庆活动方案
2014/08/16 职场文书
财会专业大学生求职信
2014/09/26 职场文书
离婚协议书范本(2016最新版)
2016/03/18 职场文书
2019年大学生学年自我鉴定!
2019/03/25 职场文书