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数据库操作面向对象的优点
Oct 09 PHP
提升PHP执行速度全攻略
Oct 09 PHP
PHP 的ArrayAccess接口 像数组一样来访问你的PHP对象
Oct 12 PHP
discuz程序的PHP加密函数原理分析
Aug 05 PHP
Linux下实现PHP多进程的方法分享
Aug 16 PHP
深入array multisort排序原理的详解
Jun 18 PHP
ThinkPHP的cookie和session冲突造成Cookie不能使用的解决方法
Jul 01 PHP
smarty内置函数foreach用法实例
Jan 22 PHP
php面向对象中static静态属性和静态方法的调用
Feb 08 PHP
php上传大文件失败的原因及应对策略
Oct 20 PHP
PHP微信支付开发实例
Jun 22 PHP
PHP实现大数(浮点数)取余的方法
Feb 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
浅析php适配器模式(Adapter)
2014/11/25 PHP
PHP超全局数组(Superglobals)介绍
2015/07/01 PHP
Redis在Laravel项目中的应用实例详解
2017/08/11 PHP
调试php程序的简单步骤
2019/10/04 PHP
用于table内容排序
2006/07/21 Javascript
开发跨浏览器javascript常见注意事项
2009/01/01 Javascript
js url传值中文乱码之解决之道
2009/11/20 Javascript
使用GruntJS构建Web程序之构建篇
2014/06/04 Javascript
jQuery实现购物车多物品数量的加减+总价计算
2014/06/06 Javascript
js实现滚动条滚动到某个位置便自动定位某个tr
2021/01/20 Javascript
使用JavaScript实现弹出层效果的简单实例
2016/05/31 Javascript
js实时获取窗口大小变化的实例代码
2016/11/18 Javascript
jquery弹窗时禁止body滚动条滚动的例子
2019/09/21 jQuery
Vue 刷新当前路由的实现代码
2019/09/26 Javascript
Javascript实现鼠标点击冒泡特效
2019/12/24 Javascript
Python中类型检查的详细介绍
2017/02/13 Python
Django 连接sql server数据库的方法
2018/06/30 Python
python梯度下降法的简单示例
2018/08/31 Python
PyCharm搭建Spark开发环境实现第一个pyspark程序
2019/06/13 Python
python3注册全局热键的实现
2020/03/22 Python
Python定时任务APScheduler安装及使用解析
2020/08/07 Python
python中编写函数并调用的知识点总结
2021/01/13 Python
Python 将代码转换为可执行文件脱离python环境运行(步骤详解)
2021/01/25 Python
html5 canvas实现跟随鼠标旋转的箭头
2016/03/11 HTML / CSS
俄罗斯最大的消费电子连锁零售商:Mvideo
2017/06/25 全球购物
幸福家庭标语
2014/06/27 职场文书
关于感恩的演讲稿500字
2014/08/26 职场文书
毕业证委托书范文
2014/09/26 职场文书
2014年“向国旗敬礼”网上签名寄语活动方案
2014/09/27 职场文书
学校政风行风整改方案
2014/10/25 职场文书
2015年工程部工作总结
2015/04/30 职场文书
关于元旦的广播稿2016
2015/12/17 职场文书
Go遍历struct,map,slice的实现
2021/06/13 Golang
MySQL深度分页(千万级数据量如何快速分页)
2021/07/25 MySQL
通过Python把学姐照片做成拼图游戏
2022/02/15 Python
SQL Server 忘记密码以及重新添加新账号
2022/04/26 SQL Server