本文主要和大家分享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格式的協議。
$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());});
這段代碼生產環境使用了半年,發現效率比較低。有些業務場入隊非常快,但處理起來所花的時間就比較長,容易出現隊列堆積現象。
增加多線程可能更有效利用硬體資源,提高業務處理能力。代碼如下
<?phpnamespace 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() {}}