MQ.php

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: brady
  5. * Date: 2017/12/6
  6. * Time: 14:42
  7. *
  8. * amqp协议操作类,可以访问rabbitMQ
  9. * 需先安装php_amqp扩展
  10. *
  11. */
  12.  
  13. class MQ
  14. {
  15. //配置
  16. public $configs = array();
  17.  
  18. //交换机名称
  19. public $exchange_name = '';
  20.  
  21. //队列名称
  22. public $queue_name = '';
  23.  
  24. //路由名称 注意 如果用同一个路由绑定交换机,当推送的时候,会同时推送到这几个key上 $q = new AMQPQueue($channel); $q->setName('queue3'); $q->setName('queue2'); $q->bind('exchange',$routingkey);
  25. public $route_key = '';
  26.  
  27. //是否持久化 默认true
  28. public $durable = true;
  29.  
  30. /*
  31. * 是否自动删除
  32. * exchange is deleted when all queues have finished using it
  33. * queue is deleted when last consumer unsubscribes
  34. *
  35. */
  36. public $auto_delete = false;
  37.  
  38. //镜像队列,打开后消息会在节点之间复制,有master和slave的概念
  39. public $mirror = false;
  40.  
  41. //连接
  42. private $_conn = NULL;
  43. //交换机对象
  44. private $_exchange = NULL;
  45. //信道对象
  46. private $_channel = NULL;
  47. //队列对象
  48. private $_queue = NULL;
  49.  
  50. /**
  51. * MQ constructor.
  52. * @configs array('host'=>$host,'port'=>5672,'username'=>$username,'password'=>$password,'vhost'=>'/')
  53. */
  54. public function __construct($configs=array(),$exchange_name='',$queue_name='',$route_key='')
  55. {
  56. $this->exchange_name = $exchange_name;
  57. $this->queue_name = $queue_name;
  58. $this->route_key = $route_key;
  59.  
  60. $this->set_configs($configs);
  61. }
  62.  
  63. /**
  64. * @desc 配置设置
  65. * @param $configs
  66. */
  67. public function set_configs($configs)
  68. {
  69. if(empty($configs) || !is_array($configs)){
  70. throw new Exception("your config is not array");
  71. }
  72.  
  73. if(empty($configs['host']) || empty($configs['username']) || empty($configs['password'])) {
  74. throw new Exception("your config is error");
  75. }
  76.  
  77. if(empty($configs['vhost'])){
  78. $configs['vhost'] = '/';
  79. }
  80.  
  81. if(empty($configs['port'])){
  82. $configs['port'] = '5672';
  83. }
  84.  
  85. $configs['login'] = $configs['username'];
  86. unset($configs['username']);
  87.  
  88. $this->configs = $configs;
  89.  
  90. }
  91.  
  92. /**
  93. * 设置是否持久化
  94. * @param $durable
  95. */
  96. public function set_durable($durable)
  97. {
  98. $this->durable = $durable;
  99. }
  100.  
  101. /**
  102. * 设置是否自动删除
  103. * @param $auto_delete boolean
  104. */
  105. public function set_auto_delete($auto_delete)
  106. {
  107. $this->auto_delete = $auto_delete;
  108. }
  109.  
  110. /**
  111. * 设置是否镜像
  112. * @param $mirror
  113. */
  114. public function set_mirror($mirror)
  115. {
  116. $this->mirror = $mirror;
  117. }
  118.  
  119. /**
  120. * 连接初始化
  121. */
  122. public function init()
  123. {
  124. //没有连接对象,进行连接 有不管 就不用每次都连接和初始化
  125. if(!$this->_conn){
  126. $this->_conn = new AMQPConnection($this->configs);
  127. $this->_conn->connect();
  128. $this->init_exchange_queue_route();
  129. }
  130. }
  131.  
  132. /**
  133. * 初始化 交换机 队列名 路由
  134. */
  135. public function init_exchange_queue_route()
  136. {
  137. if(empty($this->exchange_name) || empty($this->queue_name) || empty($this->route_key)){
  138. throw new Exception("rabbitMQ exchage_name or queue_name or route_key is empty, please check is",'500');
  139. }
  140.  
  141. //channel
  142. $this->_channel = new AMQPChannel($this->_conn);//创建channel
  143.  
  144. //exchange
  145. $this->_exchange = new AMQPExchange($this->_channel);//创建交换机
  146. $this->_exchange->setName($this->exchange_name);//设置交换机名字
  147. $this->_exchange->setType(AMQP_EX_TYPE_DIRECT);//交换机方式为direct
  148. if($this->durable) {
  149. $this->_exchange->setFlags(AMQP_DURABLE);//是否持久化
  150. }
  151. if($this->auto_delete){
  152. $this->_exchange->setFlags(AMQP_AUTODELETE);//是否自动删除
  153. }
  154. $this->_exchange->declareExchange();//申请交换机
  155.  
  156. //queue
  157. $this->_queue = new AMQPQueue($this->_channel);
  158. $this->_queue->setName($this->queue_name);
  159. if($this->durable){
  160. $this->_queue->setFlags(AMQP_DURABLE);
  161. }
  162. if($this->auto_delete){
  163. $this->_queue->setFlags(AMQP_AUTODELETE);
  164. }
  165. if($this->mirror){
  166. $this->_queue->setArgument('x-ha-policy','all');
  167. }
  168. $this->_queue->declareQueue();//申请queue
  169.  
  170. //绑定交换机
  171. $this->_queue->bind($this->exchange_name,$this->route_key);
  172. }
  173.  
  174. //关闭连接
  175. public function close()
  176. {
  177. if($this->_conn){
  178. $this->_conn->disconnect();
  179. }
  180. }
  181.  
  182. //断开连接
  183. public function __destruct()
  184. {
  185. // TODO: Implement __destruct() method.
  186. $this->close();
  187. }
  188.  
  189. //生产消息
  190. public function send($msg)
  191. {
  192. $this->init();
  193. if(!$this->_conn){
  194. throw new Exception("connect RabbitMQ failed when send message");
  195. }
  196.  
  197. if(is_array($msg)) {
  198. $msg = json_encode($msg);
  199. } else {
  200. $msg = trim(strval($msg));
  201. }
  202.  
  203. return $this->_exchange->publish($msg,$this->route_key);
  204. }
  205.  
  206. //消费消息 自动应答模式
  207. public function run_auto($funcation_name,$auto_ack = true)
  208. {
  209. $this->init();
  210. if(!$funcation_name || !$this->_queue) {
  211. throw new Exception("auto ack lose function_name or this->_queue");
  212. }
  213. while(true){
  214. if($auto_ack){
  215. $this->_queue->consume($funcation_name,AMQP_AUTOACK);
  216. } else {
  217. $this->_queue->consume($funcation_name);
  218. }
  219. }
  220.  
  221. }
  222.  
  223. }

  

my_pub.php

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: brady
  5. * Date: 2017/12/6
  6. * Time: 14:35
  7. */
  8.  
  9. require_once "MQ.php";
  10.  
  11. $configs = array(
  12. 'host'=>'192.168.33.30',
  13. 'port'=>5672,
  14. 'username'=>'title',
  15. 'password'=>'title',
  16. 'vhost'=>'/'
  17. );
  18. $number = 2;
  19. $config = [
  20. 'exchange_name'=>'brady',
  21. 'queue_name'=>"queue_".$number,
  22. 'route_key'=>"route_".$number
  23. ];
  24.  
  25. $mq = new MQ($configs,$config['exchange_name'],$config['queue_name'],$config['route_key']);
  26.  
  27. for($i=0;$i<10000;$i++){
  28. $res = $mq->send(date("Y-m-d H:i:s"));
  29. }

  my_consumer.php

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: brady
  5. * Date: 2017/12/6
  6. * Time: 19:41
  7. */
  8. require_once "MQ.php";
  9. set_time_limit(0);
  10. $configs = array(
  11. 'host'=>'192.168.33.30',
  12. 'port'=>5672,
  13. 'username'=>'title',
  14. 'password'=>'title',
  15. 'vhost'=>'/'
  16. );
  17. $number = 2;
  18. $config = [
  19. 'exchange_name'=>'brady',
  20. 'queue_name'=>"queue_".$number,
  21. 'route_key'=>"route_".$number
  22. ];
  23.  
  24. $mq = new MQ($configs,$config['exchange_name'],$config['queue_name'],$config['route_key']);
  25.  
  26. //用类的方式
  27. /*class A{
  28. function processMessage($envelope, $queue) {
  29. $msg = $envelope->getBody();
  30. $envelopeID = $envelope->getDeliveryTag();
  31. $pid = posix_getpid();
  32. file_put_contents("log{$pid}.log", $msg.'|'.$envelopeID.''."\r\n",FILE_APPEND);
  33. $queue->ack($envelopeID);
  34. }
  35. }
  36. $a = new A();*/
  37.  
  38. class B{
  39. protected $_envelope;
  40. protected $_queue;
  41. public function __construct($envelope,$queue)
  42. {
  43. $this->_queue = $queue;
  44. $this->_envelope = $envelope;
  45.  
  46. }
  47.  
  48. public function test()
  49. {
  50. $msg = $this->_envelope->getBody();
  51. $envelopeID = $this->_envelope->getDeliveryTag();
  52. $pid = posix_getpid();
  53. file_put_contents("log{$pid}.log", $msg.'|'.$envelopeID.''."\r\n",FILE_APPEND);
  54. $this->_queue->ack($envelopeID);
  55.  
  56. }
  57. }
  58.  
  59. //用函数的方式 直接在回调里面处理,也可以在回调里面,再load新的model 事务在model里面处理
  60. function processMessage($envelope, $queue) {
  61.  
  62. /* $msg = $envelope->getBody();
  63. $envelopeID = $envelope->getDeliveryTag();
  64. $pid = posix_getpid();
  65. file_put_contents("log{$pid}.log", $msg.'|'.$envelopeID.''."\r\n",FILE_APPEND);
  66. $queue->ack($envelopeID); //如果设置为AMQP_AUTOACK 那么不需要该行也可以自动应答*/
  67.  
  68. $b = new B($envelope,$queue);
  69. $b->test();
  70. }
  71.  
  72. //$s = $ra->run(array($a,'processMessage'),false);
  73. $s = $mq->run_auto("processMessage",false);

  ci里面回调函数可以传对象 比如$this  $this->tb_users 或者赋值给一个变量后传

  1. public function test_get()
  2. {
  3. $obj = $this;
  4. set_time_limit(0);
  5. require_once APPPATH."/third_party/mq/RabbitMQ.php";
  6.  
  7. $configs = array(
  8. 'host'=>'192.168.33.30',
  9. 'port'=>5672,
  10. 'username'=>'title',
  11. 'password'=>'title',
  12. 'vhost'=>'/'
  13. );
  14. $number = 2;
  15. $config = [
  16. 'exchange_name'=>'brady',
  17. 'queue_name'=>"queue_".$number,
  18. 'route_key'=>"route_".$number
  19. ];
  20. $ra = new RabbitMQ($configs,$config['exchange_name'],$config['queue_name'],$config['route_key']);
  21. $ra->run(array($obj,'processMessage'),false);
  22. }

  后面再写篇用get手动获取和响应的ack

mq类----1的更多相关文章

  1. mq类----2

    手动应答方式 使用get my_consumer.php 消费者  生产者和上一篇 一样 <?php /** * Created by PhpStorm. * User: brady * Dat ...

  2. Java类的继承与多态特性-入门笔记

    相信对于继承和多态的概念性我就不在怎么解释啦!不管你是.Net还是Java面向对象编程都是比不缺少一堂课~~Net如此Java亦也有同样的思想成分包含其中. 继承,多态,封装是Java面向对象的3大特 ...

  3. MSMQ消息队列 用法

    引言 接下来的三篇文章是讨论有关企业分布式开发的文章,这三篇文章筹划了很长时间,文章的技术并不算新,但是文章中使用到的技术都是经过笔者研究实践后总结的,正所谓站在巨人的肩膀上,笔者并不是巨人,但也希望 ...

  4. 企业数据总线(ESB)和注册服务管理(dubbo)的区别

    企业数据总线(ESB)和注册服务管理(dubbo)的区别 转载 2015年11月04日 09:05:14 7607  企业数据总线(ESB)和注册服务管理(dubbo)的区别 2015-03-09 0 ...

  5. Hadoop/Spark生态圈里的新气象

    令人惊讶的是,Hadoop在短短一年的时间里被重新定义.让我们看看这个火爆生态圈的所有主要部分,以及它们各自具有的意义. 对于Hadoop你需要了解的最重要的事情就是 ,它不再是原来的Hadoop. ...

  6. 电商技术中企业数据总线ESB和注册服务管理的区别

    一.概述 1.什么是ESB 就是企业数据总线的意思,他的核心功能就是兼容各种协议接口,可以将数据在各种协议之间进行流转,并且可以针对数据格式进行编排转换. 异构系统,功能繁多,复杂 代表性的项目有:J ...

  7. 【编码】封装RedisPubSub工具

    基本介绍 核心原理:利用Redis的List列表实现,发布事件对应rpush,订阅事件对应lpop 问题一:Redis不是自带Pub/Sub吗? redis自带的pub/sub有两个问题: 1.如果发 ...

  8. RabbitMQ,想说爱你不容易(附详细安装教程)

    前言 本文讲述的只是主要是 RabbitMQ 的入门知识,学习本文主要可以掌握以下知识点: MQ 的发展史 AMQP 协议 Rabbit MQ 的安装 Rabbit MQ 在 Java API 中的使 ...

  9. IBM WebSphere MQ的C#工具类以及源码(net)

    简单的介绍一下MQ常用的对象 Queue Manager 队列管理器 主要负责管理队列.通道等,类似与Oracle中的Oracle实例的概念,在一台服务器中可以定义多个Queue Manager. Q ...

随机推荐

  1. Python+selenium之获取验证信息

    通常获取验证信息用得最多的几种验证信息分别是title,URL和text.text方法用于获取标签对之间的文本信息. 代码如下: from selenium import webdriverimpor ...

  2. JSON 序列化格式

    一.C#处理简单json数据json数据: 复制代码代码如下: {"result":"0","res_info":"ok" ...

  3. CentOS6.4安装JDK,卸载自带的OpenJDK

    1.查看OpenJDK的安装包 $ rpm -qa |grep java java-1.6.0-openjdk-1.6.0.0-1.62.1.11.11.90.el6_4.x86_64 java-1. ...

  4. Python使用easy-install安装时报UnicodeDecodeError的解决方法

    Python使用easy-install安装时报UnicodeDecodeError的解决方法,有需要的朋友可以参考下. 问题描述: 在使用easy-install安装matplotlib.pypar ...

  5. 【TensorFlow入门完全指南】模型篇·最近邻模型

    最近邻模型,更为常见的是k-最近邻模型,是一种常见的机器学习模型,原理如下: KNN算法的前提是存在一个样本的数据集,每一个样本都有自己的标签,表明自己的类型.现在有一个新的未知的数据,需要判断它的类 ...

  6. 如何使用动画库animate.css

    animate.css是一个CSS3动画库,里面预设了抖动(shake).闪烁(flash).弹跳(bounce).翻转(flip).旋转(rotateIn/rotateOut).淡入淡出(fadeI ...

  7. stm32F042 (二) 按键触发中断

    已经实现GPIO口输出高低电平控制LED,这里实现按键触发中断来改变LED闪亮的频率,因为PB3连着LED,所以PB3的输出模式没有改变,随意选一个GPIO口PA7接按键产生中断.因为nucleo开发 ...

  8. Python——函数入门(二)

    一.函数的参数 我们在定义函数时,可以定义形式参数(简称形参),这些形参的值在函数调用的时候才会确定,形参的值由调用者负责传入. 1.关键字参数 在Python中,函数的参数名并不是没有意义的,在调用 ...

  9. skynet 学习笔记-sproto模块(2)

    云风在skynet中继承了sproto的传输协议,对比protobuf的好处是,能明文看到传输内容,而且skynet不需要protobuf这么功能,所以云风也建议在lua层使用sproto来作为sky ...

  10. python元组的相对不可变性

    元组与多数python集合(列表.字典.集,等等)一样,保存的是对象的引用.如果引用的元素是可变的,即便元组本身不可变,但是元素依然可变.也就是说元组的不可变性其实是指tuple数据结构的物理内容(即 ...