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&amp;MYSQL分页原理及实现
Jan 02 PHP
php cout&amp;lt;&amp;lt;的一点看法
Jan 24 PHP
PHP foreach循环使用详解与实例代码
May 08 PHP
php+ajax做仿百度搜索下拉自动提示框(有实例)
Aug 21 PHP
用Php编写注册后Email激活验证的实例代码
Mar 11 PHP
phpmyadmin config.inc.php配置示例
Aug 27 PHP
PHP函数microtime()用法与说明
Dec 04 PHP
php fsockopen解决办法 php实现多线程
Jan 20 PHP
PHP编程实现微信企业向用户付款的方法示例
Jul 26 PHP
CI框架(CodeIgniter)公共模型类定义与用法示例
Aug 10 PHP
PHP PDO和消息队列的个人理解与应用实例分析
Nov 25 PHP
php远程请求CURL实例教程(爬虫、保存登录状态)
Dec 10 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
Ecshop 后台添加新功能栏目及管理权限设置教程
2017/11/21 PHP
javascript中select下拉框的用法总结
2016/01/07 Javascript
非常棒的jQuery图片轮播效果
2016/04/17 Javascript
JavaScript 函数的执行过程
2016/05/09 Javascript
JS禁止查看网页源代码的实现方法
2016/10/12 Javascript
Bootstrap DateTime Picker日历控件简单应用
2017/03/25 Javascript
nodejs和C语言插入mysql数据库乱码问题的解决方法
2017/04/14 NodeJs
Node.js简单入门前传
2017/08/21 Javascript
Angular4的输入属性与输出属性实例详解
2017/11/29 Javascript
JavaScript自动生成 年月范围 选择功能完整示例【基于jQuery插件】
2019/09/03 jQuery
jquery.validate自定义验证用法实例分析【成功提示与择要提示】
2020/06/06 jQuery
vuex实现购物车的增加减少移除
2020/06/28 Javascript
python 域名分析工具实现代码
2009/07/15 Python
python 图片验证码代码分享
2012/07/04 Python
跟老齐学Python之开始真正编程
2014/09/12 Python
Java实现的执行python脚本工具类示例【使用jython.jar】
2018/03/29 Python
python清除函数占用的内存方法
2018/06/25 Python
10个Python小技巧你值得拥有
2018/09/29 Python
Tensorflow 多线程设置方式
2020/02/06 Python
python实现数字炸弹游戏
2020/07/17 Python
Ubuntu16安装Python3.9的实现步骤
2020/12/15 Python
详解css position 5种不同的值的用法
2019/07/30 HTML / CSS
加拿大折扣、优惠券和交易网站:WagJag
2018/02/07 全球购物
编写函数,将一个3*3矩阵转置
2013/10/09 面试题
护士自荐信
2013/10/25 职场文书
总经理助理的职责
2014/03/14 职场文书
投资协议书范本
2014/04/21 职场文书
有关爱国演讲稿
2014/05/07 职场文书
企业安全生产承诺书
2014/05/22 职场文书
园艺专业毕业生求职信
2014/09/02 职场文书
师德师风事迹材料
2014/12/20 职场文书
2016年学校招生广告语
2016/01/28 职场文书
Redis持久化与主从复制的实践
2021/04/27 Redis
动画《新网球王子 U-17 WORLD CUP》希腊队PV公开
2022/04/02 日漫
详解Android中的TimePickerView(时间选择器)的用法
2022/04/30 Java/Android
MySQL添加索引特点及优化问题
2022/07/23 MySQL