当前位置:首页 > PHP教程 > php高级应用 > 列表

PHP高级编程之消息队列原理与实现方法详解

发布:smiling 来源: PHP粉丝网  添加日期:2022-02-05 10:14:22 浏览: 评论:0 

本文实例讲述了PHP高级编程之消息队列原理与实现方法, 分享给大家供大家参考,具体如下:

1. 什么是消息队列

消息队列(英语:Message queue)是一种进程间通信或同一进程的不同线程间的通信方式

2. 为什么使用消息队列

消息队列技术是分布式应用间交换信息的一种技术。消息队列可驻留在内存或磁盘上,队列存储消息直到它们被应用程序读出。通过消息队列,应用程序可独立地执行,它们不需要知道彼此的位置、或在继续执行前不需要等待接收程序接收此消息。

3. 什么场合使用消息队列

你首先需要弄清楚,消息队列与远程过程调用的区别,在很多读者咨询我的时候,我发现他们需要的是RPC(远程过程调用),而不是消息队列。

消息队列有同步或异步实现方式,通常我们采用异步方式使用消息队列,远程过程调用多采用同步方式。

MQ与RPC有什么不同? MQ通常传递无规则协议,这个协议由用户定义并且实现存储转发;而RPC通常是专用协议,调用过程返回结果。

4. 什么时候使用消息队列

同步需求,远程过程调用(PRC)更适合你。

异步需求,消息队列更适合你。

目前很多消息队列软件同时支持RPC功能,很多RPC系统也能异步调用。

消息队列用来实现下列需求

① 存储转发

② 分布式事务

③ 发布订阅

④ 基于内容的路由

⑤ 点对点连接

5. 谁负责处理消息队列

通常的做法,如果小的项目团队可以有一个人实现,包括消息的推送,接收处理。如果大型团队,通常是定义好消息协议,然后各自开发各自的部分,例如一个团队负责写推送协议部分,另一个团队负责写接收与处理部分。

那么为什么我们不讲消息队列框架化呢?

框架化有几个好处:

① 开发者不用学习消息队列接口

② 开发者不需要关心消息推送与接收

③ 开发者通过统一的API推送消息

④ 开发者的重点是实现业务逻辑功能

6. 怎么实现消息队列框架

下面是作者开发的一个SOA框架,该框架提供了三种接口,分别是SOAP,RESTful,AMQP(RabbitMQ),理解了该框架思想,你很容易进一步扩展,例如增加XML-RPC, ZeroMQ等等支持。

https://github.com/netkiller/SOA

本文只讲消息队列框架部分。

6.1. 守护进程

消息队列框架是本地应用程序(命令行程序),我们为了让他在后台运行,需要实现守护进程。

https://github.com/netkiller/SOA/blob/master/bin/rabbitmq.php

每个实例处理一组队列,实例化需要提供三个参数,$queueName = '队列名', $exchangeName = '交换名', $routeKey = '路由'

$daemon = new \framework\RabbitDaemon($queueName = 'email', $exchangeName = 'email', $routeKey = 'email');

守护进程需要使用root用户运行,运行后会切换到普通用户,同时创建进程ID文件,以便进程停止的时候使用。

守护进程核心代码https://github.com/netkiller/SOA/blob/master/system/rabbitdaemon.class.php

6.2. 消息队列协议

消息协议是一个数组,将数组序列化或者转为JSON推送到消息队列服务器,这里使用json格式的协议。

  1. $msg = array( 
  2.     'Namespace'=>'namespace', 
  3.     "Class"=>"Email", 
  4.     "Method"=>"smtp", 
  5.     "Param" => array( 
  6.         $mail, $subject, $message, null 
  7.     ) 
  8. ); 

序列化后的协议

{"Namespace":"single","Class":"Email","Method":"smtp","Param":["netkiller@msn.com","Hello"," TestHelloWorld",null]}

使用json格式是考虑到通用性,这样推送端可以使用任何语言。如果不考虑兼容,建议使用二进制序列化,例如msgpack效率更好。

6.3. 消息队列处理

消息队列处理核心代码

https://github.com/netkiller/SOA/blob/master/system/rabbitmq.class.php

所以消息的处理在下面一段代码中进行

  1. $this->queue->consume(function($envelope, $queue) { 
  2.     $speed = microtime(true); 
  3.     $msg = $envelope->getBody(); 
  4.     $result = $this->loader($msg); 
  5.     $queue->ack($envelope->getDeliveryTag()); //手动发送ACK应答 
  6.     //$this->logging->info(''.$msg.' '.$result) 
  7.     $this->logging->debug('Protocol: '.$msg.' '); 
  8.     $this->logging->debug('Result: '. $result.' '); 
  9.     $this->logging->debug('Time: '. (microtime(true) - $speed) .''); 
  10. }); 

public function loader($msg = null) 负责拆解协议,然后载入对应的类文件,传递参数,运行方法,反馈结果。

Time 可以输出程序运行所花费的时间,对于后期优化十分有用。

提示

loader() 可以进一步优化,使用多线程每次调用loader将任务提交到线程池中,这样便可以多线程处理消息队列。

6.4. 测试

测试代码 https://github.com/netkiller/SOA/blob/master/test/queue/email.php

  1. <?php 
  2. $queueName = 'example'; 
  3. $exchangeName = 'email'; 
  4. $routeKey = 'email'; 
  5. $mail = $argv[1]; 
  6. $subject = $argv[2]; 
  7. $message = emptyempty($argv[3]) ? 'Hello World!' : ' '.$argv[3]; 
  8. $connection = new AMQPConnection(array( 
  9.     'host' => '192.168.4.1', 
  10.     'port' => '5672', 
  11.     'vhost' => '/', 
  12.     'login' => 'guest', 
  13.     'password' => 'guest' 
  14.     )); 
  15. $connection->connect() or die("Cannot connect to the broker!\n"); 
  16. $channel = new AMQPChannel($connection); 
  17. $exchange = new AMQPExchange($channel); 
  18. $exchange->setName($exchangeName); 
  19. $queue = new AMQPQueue($channel); 
  20. $queue->setName($queueName); 
  21. $queue->setFlags(AMQP_DURABLE); 
  22. $queue->declareQueue(); 
  23. $msg = array( 
  24.     'Namespace'=>'namespace', 
  25.     "Class"=>"Email", 
  26.     "Method"=>"smtp", 
  27.     "Param" => array( 
  28.         $mail, $subject, $message, null 
  29.     ) 
  30. ); 
  31. $exchange->publish(json_encode($msg), $routeKey); 
  32. printf("[x] Sent %s \r\n", json_encode($msg)); 
  33. $connection->disconnect(); 

这里只给出了少量测试与演示程序,如有疑问请到渎者群,或者公众号询问。

7. 多线程

上面消息队列 核心代码如下

  1. $this->queue->consume(function($envelope, $queue) { 
  2.     $msg = $envelope->getBody(); 
  3.     $result = $this->loader($msg); 
  4.     $queue->ack($envelope->getDeliveryTag()); 
  5. }); 

这段代码生产环境使用了半年,发现效率比较低,有些业务场入队非常快,但处理起来所花的时间就比较长,容易出现队列堆积现象。

增加多线程可能更有效利用硬件资源,提高业务处理能力,代码如下

  1. <?php 
  2. namespace framework; 
  3. require_once( __DIR__.'/autoload.class.php' ); 
  4. class RabbitThread extends \Threaded { 
  5.     private $queue; 
  6.     public $classspath; 
  7.     protected $msg; 
  8.     public function __construct($queue, $logging, $msg) { 
  9.         $this->classspath = __DIR__.'/../queue'; 
  10.         $this->msg = $msg; 
  11.         $this->logging = $logging; 
  12.         $this->queue = $queue; 
  13.     } 
  14.     public function run() { 
  15.         $speed = microtime(true); 
  16.         $result = $this->loader($this->msg); 
  17.         $this->logging->debug('Result: '. $result.' '); 
  18.         $this->logging->debug('Time: '. (microtime(true) - $speed) .''); 
  19.     } 
  20.     // private 
  21.     public function loader($msg = null){ 
  22.         $protocol     = json_decode($msg,true); 
  23.         $namespace    = $protocol['Namespace']; 
  24.         $class         = $protocol['Class']; 
  25.         $method     = $protocol['Method']; 
  26.         $param         = $protocol['Param']; 
  27.         $result     = null; 
  28.         $classspath = $this->classspath.'/'.$this->queue.'/'.$namespace.'/'.strtolower($class) . '.class.php'; 
  29.         if( is_file($classspath) ){ 
  30.             require_once($classspath); 
  31.             //$class = ucfirst(substr($request_uri, strrpos($request_uri, '/')+1)); 
  32.             if (class_exists($class)) { 
  33.                 if(method_exists($class, $method)){ 
  34.                     $obj = new $class; 
  35.                     if (!$param){ 
  36.                         $tmp = $obj->$method(); 
  37.                         $result = json_encode($tmp); 
  38.                         $this->logging->info($class.'->'.$method.'()'); 
  39.                     }else{ 
  40.                         $tmp = call_user_func_array(array($obj, $method), $param); 
  41.                         $result = (json_encode($tmp)); 
  42.                         $this->logging->info($class.'->'.$method.'("'.implode('","', $param).'")'); 
  43.                     } 
  44.                 }else{ 
  45.                     $this->logging->error('Object '. $class. '->' . $method. ' is not exist.'); 
  46.                 } 
  47.             }else{ 
  48.                 $msg = sprintf("Object is not exist. (%s)", $class); 
  49.                 $this->logging->error($msg); 
  50.             } 
  51.         }else{ 
  52.             $msg = sprintf("Cannot loading interface! (%s)", $classspath); 
  53.             $this->logging->error($msg); 
  54.         } 
  55.         return $result; 
  56.     } 
  57. } 
  58. class RabbitMQ { 
  59.     const loop = 10; 
  60.     protected $queue; 
  61.     protected $pool; 
  62.     public function __construct($queueName = '', $exchangeName = '', $routeKey = '') { 
  63.         $this->config = new \framework\Config('rabbitmq.ini'); 
  64.         $this->logfile = __DIR__.'/../log/rabbitmq.%s.log'; 
  65.         $this->logqueue = __DIR__.'/../log/queue.%s.log'; 
  66.         $this->logging = new \framework\log\Logging($this->logfile, $debug=true); 
  67.  //.H:i:s 
  68.         $this->queueName    = $queueName; 
  69.         $this->exchangeName    = $exchangeName; 
  70.         $this->routeKey        = $routeKey; 
  71.         $this->pool = new \Pool($this->config->get('pool')['thread']); 
  72.     } 
  73.     public function main(){ 
  74.         $connection = new \AMQPConnection($this->config->get('rabbitmq')); 
  75.         try { 
  76.             $connection->connect(); 
  77.             if (!$connection->isConnected()) { 
  78.                 $this->logging->exception("Cannot connect to the broker!" 
  79. .PHP_EOL); 
  80.             } 
  81.             $this->channel = new \AMQPChannel($connection); 
  82.             $this->exchange = new \AMQPExchange($this->channel); 
  83.             $this->exchange->setName($this->exchangeName); 
  84.             $this->exchange->setType(AMQP_EX_TYPE_DIRECT); //direct类型 
  85.             $this->exchange->setFlags(AMQP_DURABLE); //持久�? 
  86.             $this->exchange->declareExchange(); 
  87.             $this->queue = new \AMQPQueue($this->channel); 
  88.             $this->queue->setName($this->queueName); 
  89.             $this->queue->setFlags(AMQP_DURABLE); //持久�? 
  90.             $this->queue->declareQueue(); 
  91.             $this->queue->bind($this->exchangeName, $this->routeKey); 
  92.             $this->queue->consume(function($envelope, $queue) { 
  93.                 $msg = $envelope->getBody(); 
  94.                 $this->logging->debug('Protocol: '.$msg.' '); 
  95.                 //$result = $this->loader($msg); 
  96.                 $this->pool->submit(new RabbitThread($this->queueName, 
  97. new \framework\log\Logging($this->logqueue, $debug=true), $msg)); 
  98.                 $queue->ack($envelope->getDeliveryTag()); 
  99.             }); 
  100.             $this->channel->qos(0,1); 
  101.         } 
  102.         catch(\AMQPConnectionException $e){ 
  103.             $this->logging->exception($e->__toString()); 
  104.         } 
  105.         catch(\Exception $e){ 
  106.             $this->logging->exception($e->__toString()); 
  107.             $connection->disconnect(); 
  108.             $this->pool->shutdown(); 
  109.         } 
  110.     } 
  111.     private function fault($tag, $msg){ 
  112.         $this->logging->exception($msg); 
  113.         throw new \Exception($tag.': '.$msg); 
  114.     } 
  115.     public function __destruct() { 
  116.     } 
  117. }

Tags: PHP消息队列

分享到: