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 相关文章推荐
第1次亲密接触PHP5(1)
Oct 09 PHP
php 异常处理实现代码
Mar 10 PHP
用PHP获取Google AJAX Search API 数据的代码
Mar 12 PHP
php动态实现表格跨行跨列实现代码
Nov 06 PHP
php获取服务器端mac和客户端mac的地址支持WIN/LINUX
May 15 PHP
php封装的连接Mysql类及用法分析
Dec 10 PHP
浅谈Yii乐观锁的使用及原理
Jul 25 PHP
PHP实现深度优先搜索算法(DFS,Depth First Search)详解
Sep 16 PHP
Laravel 加载第三方类库的方法
Apr 20 PHP
laravel 实现向公共模板中传值 (view composer)
Oct 22 PHP
laravel 出现command not found问题的解决方案
Oct 23 PHP
6个常见的 PHP 安全性攻击实例和阻止方法
Dec 16 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 生成WML页面方法详解
2009/08/09 PHP
php的一些小问题
2010/07/03 PHP
php中防止伪造跨站请求的小招式
2011/09/02 PHP
php根据身份证号码计算年龄的实例代码
2014/01/18 PHP
php实现遍历目录并删除指定文件中指定内容
2015/01/21 PHP
php实现的XML操作(读取)封装类完整实例
2017/02/23 PHP
cakephp常见知识点汇总
2017/02/24 PHP
PHP 获取客户端 IP 地址的方法实例代码
2018/11/11 PHP
js弹出div并显示遮罩层
2014/02/12 Javascript
javascript实现在网页任意处点左键弹出隐藏菜单的方法
2015/05/13 Javascript
jQuery视差滚动效果网页实现方法经验总结
2016/09/29 Javascript
通过构造函数实例化对象的方法
2017/06/28 Javascript
利用vue.js实现被选中状态的改变方法
2018/02/08 Javascript
浅入深出Vue之组件使用
2019/07/11 Javascript
[03:41]2018完美盛典-《Fight With Us》
2018/12/16 DOTA
python基础教程之简单入门说明(变量和控制语言使用方法)
2014/03/25 Python
python检测某个变量是否有定义的方法
2015/05/20 Python
一道python走迷宫算法题
2018/01/22 Python
使用PIL(Python-Imaging)反转图像的颜色方法
2019/01/24 Python
基于MATLAB和Python实现MFCC特征参数提取
2019/08/13 Python
简单了解Java Netty Reactor三种线程模型
2020/04/26 Python
python使用hdfs3模块对hdfs进行操作详解
2020/06/06 Python
解决运行出现'dict' object has no attribute 'has_key'问题
2020/07/15 Python
pycharm2020.1.2永久破解激活教程,实测有效
2020/10/29 Python
python中的列表和元组区别分析
2020/12/30 Python
阿迪达斯意大利在线商店:adidas意大利
2016/09/19 全球购物
Paradox London官方网站:英国新娘鞋婚礼鞋品牌
2019/08/29 全球购物
小学教师管理制度
2014/01/18 职场文书
高二政治教学反思
2014/02/01 职场文书
中学生操行评语大全
2014/04/24 职场文书
《少年王勃》教学反思
2014/04/27 职场文书
倡议书格式模板
2014/05/13 职场文书
英文导游词
2015/02/13 职场文书
2016大学生入党积极分子心得体会
2016/01/06 职场文书
《伯牙绝弦》教学反思
2016/02/16 职场文书
利用Pycharm连接服务器的全过程记录
2021/07/01 Python