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 相关文章推荐
从零开始 教你如何搭建Discuz!4.1论坛
Jul 07 PHP
简单采集了yahoo的一些数据
Feb 14 PHP
php strcmp使用说明
Apr 22 PHP
国外PHP程序员的13个好习惯小结
Feb 20 PHP
PHP应用JSON技巧讲解
Feb 03 PHP
Codeigniter+PHPExcel实现导出数据到Excel文件
Jun 12 PHP
PHP实现二叉树的深度优先与广度优先遍历方法
Sep 28 PHP
php实现的网页版剪刀石头布游戏示例
Nov 25 PHP
laravel框架的安装与路由实例分析
Oct 11 PHP
php文件上传原理与实现方法详解
Dec 20 PHP
gearman中worker常驻后台,导致MySQL server has gone away的解决方法
Feb 27 PHP
PHP unset函数原理及使用方法解析
Aug 14 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也可以?成Shell Script
2006/10/09 PHP
PHP和.net中des加解密的实现方法
2013/02/27 PHP
PHP框架Laravel的小技巧两则
2015/02/10 PHP
thinkPHP5实现数据库添加内容的方法
2017/10/25 PHP
详解json在php中的应用
2018/09/30 PHP
Laravel框架控制器,视图及模型操作图文详解
2019/12/04 PHP
ExtJs的Date格式字符代码
2010/12/30 Javascript
JQuery中html()方法使用不当带来的陷阱
2011/04/07 Javascript
js获取指定的cookie的具体实现
2014/02/20 Javascript
Javascript常用小技巧汇总
2015/06/24 Javascript
12 款 JS 代码测试必备工具(翻译)
2016/12/13 Javascript
Vue.js实现表格动态增加删除的方法(附源码下载)
2017/01/20 Javascript
浅谈js闭包理解
2019/03/28 Javascript
了解在JavaScript中将值转换为字符串的5种方法
2019/06/06 Javascript
基于ajax实现上传图片代码示例解析
2020/12/03 Javascript
[54:15]DOTA2-DPC中国联赛 正赛 DLG vs Dragon BO3 第二场2月1日
2021/03/11 DOTA
Python操作CouchDB数据库简单示例
2015/03/10 Python
Python Tkinter GUI编程入门介绍
2015/03/10 Python
Python自动登录126邮箱的方法
2015/07/10 Python
Python中for循环和while循环的基本使用方法
2015/08/21 Python
Python实现网络端口转发和重定向的方法
2016/09/19 Python
pygame游戏之旅 python和pygame安装教程
2018/11/20 Python
在Python 字典中一键对应多个值的实例
2019/02/03 Python
python爬虫租房信息在地图上显示的方法
2019/05/13 Python
python爬虫模块URL管理器模块用法解析
2020/02/03 Python
tensorflow pb to tflite 精度下降详解
2020/05/25 Python
美国标志性加大尺码时装品牌:Ashley Stewart
2016/12/15 全球购物
Larsson & Jennings官网:现代瑞士钟表匠
2018/03/20 全球购物
上班早退检讨书
2014/01/09 职场文书
大学生职业规划书的范本
2014/02/18 职场文书
工作建议书范文
2014/05/13 职场文书
优秀班主任先进事迹材料
2014/12/16 职场文书
物业工程部经理岗位职责
2015/04/09 职场文书
2015年社区平安建设工作总结
2015/05/13 职场文书
校长新学期寄语2016
2015/12/04 职场文书
剖析后OpLog订阅MongoDB的数据变更就没那么难了
2022/02/24 MongoDB