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!5的PHP代码高亮显示与实现可运行代码
Mar 15 PHP
php下将XML转换为数组
Jan 01 PHP
基于flush()不能按顺序输出时的解决办法
Jun 29 PHP
PHP中替换键名的简易方法示例详解
Jan 07 PHP
CI框架入门示例之数据库取数据完整实现方法
Nov 05 PHP
php一行代码获取文件后缀名实例分析
Nov 12 PHP
yii的CURD操作实例详解
Dec 04 PHP
PHP向socket服务器收发数据的方法
Jan 24 PHP
隐藏Nginx或Apache以及PHP的版本号的方法
Jan 03 PHP
Yii2框架使用计划任务的方法
May 25 PHP
php array_values 返回数组的所有值详解及实例
Nov 12 PHP
php反序列化长度变化尾部字符串逃逸(0CTF-2016-piapiapia)
Feb 15 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笔试题
2009/08/04 PHP
php文件读取方法实例分析
2015/06/20 PHP
PHP处理二进制数据的实现方法
2016/06/13 PHP
JavaScript 学习笔记(十五)
2010/01/28 Javascript
js中对象的声明方式以及数组的一些用法示例
2013/12/11 Javascript
js在数组中删除重复的元素自保留一个(两种实现思路)
2014/08/22 Javascript
js实现select跳转菜单新窗口效果代码分享(超简单)
2015/08/21 Javascript
微信小程序 生命周期详解
2016/10/12 Javascript
微信小程序button组件使用详解
2018/01/31 Javascript
jQuery模拟html下拉多选框的原生实现方法示例
2019/05/30 jQuery
element-plus一个vue3.xUI框架(element-ui的3.x 版初体验)
2020/12/02 Vue.js
vue下拉刷新组件的开发及slot的使用详解
2020/12/23 Vue.js
[01:25:09]2014 DOTA2国际邀请赛中国区预选赛 5 23 CIS VS DT第二场
2014/05/24 DOTA
利用Python开发实现简单的记事本
2016/11/15 Python
python利用正则表达式提取字符串
2016/12/08 Python
Python脚本获取操作系统版本信息
2016/12/17 Python
Python内置函数delattr的具体用法
2017/11/23 Python
ubuntu17.4下为python和python3装上pip的方法
2018/06/12 Python
对python自动生成接口测试的示例讲解
2018/11/30 Python
Python基于Tkinter模块实现的弹球小游戏
2018/12/27 Python
Python设计模式之职责链模式原理与用法实例分析
2019/01/11 Python
Python中使用遍历在列表中添加字典遇到的坑
2019/02/27 Python
python儿童学游戏编程知识点总结
2019/06/03 Python
Python使用pyserial进行串口通信的实例
2019/07/02 Python
通过python 执行 nohup 不生效的解决
2020/04/16 Python
python和php哪个容易学
2020/06/19 Python
SmartBuyGlasses英国:购买太阳镜和眼镜
2018/01/29 全球购物
有趣的流行文化T恤、马克杯、手机壳和更多:Look Human
2019/01/07 全球购物
Spartoo美国:欧洲排名第一的在线时装零售商
2019/12/12 全球购物
给排水专业应届生求职信
2013/10/12 职场文书
小溪流的歌教学反思
2014/02/13 职场文书
银行办公室岗位职责
2014/03/10 职场文书
我为党旗添光彩演讲稿
2014/09/10 职场文书
2014年精神文明工作总结
2014/12/23 职场文书
Mysql外键约束的创建与删除的使用
2022/03/03 MySQL
Redis唯一ID生成器的实现
2022/07/07 Redis