PHP高级编程之消息队列
1.?什么是消息隊列
消息隊列(英語:Message queue)是一種進程間通信或同一進程的不同線程間的通信方式
2.?為什么使用消息隊列
消息隊列技術是分布式應用間交換信息的一種技術。消息隊列可駐留在內存或磁盤上,隊列存儲消息直到它們被應用程序讀出。通過消息隊列,應用程序可獨立地執行,它們不需要知道彼此的位置、或在繼續執行前不需要等待接收程序接收此消息。
3.?什么場合使用消息隊列
你首先需要弄清楚,消息隊列與遠程過程調用的區別,在很多讀者咨詢我的時候,我發現他們需要的是RPC(遠程過程調用),而不是消息隊列。
消息隊列有同步或異步實現方式,通常我們采用異步方式使用消息隊列,遠程過程調用多采用同步方式。
MQ與RPC有什么不同? MQ通常傳遞無規則協議,這個協議由用戶定義并且實現存儲轉發;而RPC通常是專用協議,調用過程返回結果。
4.?什么時候使用消息隊列
同步需求,遠程過程調用(PRC)更適合你。
異步需求,消息隊列更適合你。
目前很多消息隊列軟件同時支持RPC功能,很多RPC系統也能異步調用。
消息隊列用來實現下列需求存儲轉發
分布式事務
發布訂閱
基于內容的路由
點對點連接
5.?誰負責處理消息隊列
通常的做法,如果小的項目團隊可以有一個人實現,包括消息的推送,接收處理。如果大型團隊,通常是定義好消息協議,然后各自開發各自的部分,例如一個團隊負責寫推送協議部分,另一個團隊負責寫接收與處理部分。
那么為什么我們不講消息隊列框架化呢?
框架化有幾個好處: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格式的協議。
$msg = array('Namespace'=>'namespace',"Class"=>"Email","Method"=>"smtp","Param" => array($mail, $subject, $message, null) );序列化后的協議
{"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
所以消息的處理在下面一段代碼中進行
$this->queue->consume(function($envelope, $queue) {$speed = microtime(true);$msg = $envelope->getBody();$result = $this->loader($msg);$queue->ack($envelope->getDeliveryTag()); //手動發送ACK應答//$this->logging->info(''.$msg.' '.$result)$this->logging->debug('Protocol: '.$msg.' ');$this->logging->debug('Result: '. $result.' ');$this->logging->debug('Time: '. (microtime(true) - $speed) .''); });public function loader($msg = null) 負責拆解協議,然后載入對應的類文件,傳遞參數,運行方法,反饋結果。
Time 可以輸出程序運行所花費的時間,對于后期優化十分有用。
提示
loader() 可以進一步優化,使用多線程每次調用loader將任務提交到線程池中,這樣便可以多線程處理消息隊列。
6.4.?測試
測試代碼?https://github.com/netkiller/SOA/blob/master/test/queue/email.php
<?php $queueName = 'example'; $exchangeName = 'email'; $routeKey = 'email'; $mail = $argv[1]; $subject = $argv[2]; $message = empty($argv[3]) ? 'Hello World!' : ' '.$argv[3];$connection = new AMQPConnection(array('host' => '192.168.4.1', 'port' => '5672', 'vhost' => '/', 'login' => 'guest', 'password' => 'guest')); $connection->connect() or die("Cannot connect to the broker!\n");$channel = new AMQPChannel($connection); $exchange = new AMQPExchange($channel); $exchange->setName($exchangeName); $queue = new AMQPQueue($channel); $queue->setName($queueName); $queue->setFlags(AMQP_DURABLE); $queue->declareQueue();$msg = array('Namespace'=>'namespace',"Class"=>"Email","Method"=>"smtp","Param" => array($mail, $subject, $message, null) );$exchange->publish(json_encode($msg), $routeKey); printf("[x] Sent %s \r\n", json_encode($msg));$connection->disconnect();這里只給出了少量測試與演示程序,如有疑問請到瀆者群,或者公眾號詢問。
7.?多線程
上面消息隊列 核心代碼如下
$this->queue->consume(function($envelope, $queue) { $msg = $envelope->getBody();$result = $this->loader($msg);$queue->ack($envelope->getDeliveryTag()); });這段代碼生產環境使用了半年,發現效率比較低。有些業務場入隊非常快,但處理起來所花的時間就比較長,容易出現隊列堆積現象。
增加多線程可能更有效利用硬件資源,提高業務處理能力。代碼如下
<?php namespace framework;require_once( __DIR__.'/autoload.class.php' );class RabbitThread extends \Threaded {private $queue;public $classspath;protected $msg;public function __construct($queue, $logging, $msg) {$this->classspath = __DIR__.'/../queue';$this->msg = $msg;$this->logging = $logging;$this->queue = $queue;}public function run() {$speed = microtime(true);$result = $this->loader($this->msg);$this->logging->debug('Result: '. $result.' ');$this->logging->debug('Time: '. (microtime(true) - $speed) .'');}// privatepublic function loader($msg = null){$protocol = json_decode($msg,true);$namespace = $protocol['Namespace'];$class = $protocol['Class'];$method = $protocol['Method'];$param = $protocol['Param'];$result = null;$classspath = $this->classspath.'/'.$this->queue.'/'.$namespace.'/'.strtolower($class) . '.class.php';if( is_file($classspath) ){require_once($classspath);//$class = ucfirst(substr($request_uri, strrpos($request_uri, '/')+1));if (class_exists($class)) {if(method_exists($class, $method)){$obj = new $class;if (!$param){$tmp = $obj->$method();$result = json_encode($tmp);$this->logging->info($class.'->'.$method.'()');}else{$tmp = call_user_func_array(array($obj, $method), $param);$result = (json_encode($tmp));$this->logging->info($class.'->'.$method.'("'.implode('","', $param).'")');}}else{$this->logging->error('Object '. $class. '->' . $method. ' is not exist.');}}else{$msg = sprintf("Object is not exist. (%s)", $class);$this->logging->error($msg);}}else{$msg = sprintf("Cannot loading interface! (%s)", $classspath);$this->logging->error($msg);}return $result;} }class RabbitMQ {const loop = 10;protected $queue;protected $pool;public function __construct($queueName = '', $exchangeName = '', $routeKey = '') {$this->config = new \framework\Config('rabbitmq.ini');$this->logfile = __DIR__.'/../log/rabbitmq.%s.log';$this->logqueue = __DIR__.'/../log/queue.%s.log';$this->logging = new \framework\log\Logging($this->logfile, $debug=true);//.H:i:s$this->queueName = $queueName;$this->exchangeName = $exchangeName;$this->routeKey = $routeKey; $this->pool = new \Pool($this->config->get('pool')['thread']);}public function main(){$connection = new \AMQPConnection($this->config->get('rabbitmq'));try {$connection->connect();if (!$connection->isConnected()) {$this->logging->exception("Cannot connect to the broker!" .PHP_EOL);}$this->channel = new \AMQPChannel($connection);$this->exchange = new \AMQPExchange($this->channel);$this->exchange->setName($this->exchangeName);$this->exchange->setType(AMQP_EX_TYPE_DIRECT); //direct類型$this->exchange->setFlags(AMQP_DURABLE); //持久�?$this->exchange->declareExchange();$this->queue = new \AMQPQueue($this->channel);$this->queue->setName($this->queueName);$this->queue->setFlags(AMQP_DURABLE); //持久�?$this->queue->declareQueue();$this->queue->bind($this->exchangeName, $this->routeKey);$this->queue->consume(function($envelope, $queue) {$msg = $envelope->getBody();$this->logging->debug('Protocol: '.$msg.' ');//$result = $this->loader($msg);$this->pool->submit(new RabbitThread($this->queueName, new \framework\log\Logging($this->logqueue, $debug=true), $msg));$queue->ack($envelope->getDeliveryTag()); });$this->channel->qos(0,1);}catch(\AMQPConnectionException $e){$this->logging->exception($e->__toString());}catch(\Exception $e){$this->logging->exception($e->__toString());$connection->disconnect();$this->pool->shutdown();}}private function fault($tag, $msg){$this->logging->exception($msg);throw new \Exception($tag.': '.$msg);}public function __destruct() {} }總結
以上是生活随笔為你收集整理的PHP高级编程之消息队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows下安装并设置Redis
- 下一篇: 分块查询 缓解内存开销