首頁  >  文章  >  後端開發  >  PHP訊息佇列詳解

PHP訊息佇列詳解

小云云
小云云原創
2018-03-27 09:29:463886瀏覽

本文主要和大家分享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

d59d185a8fe5ed4100dde982382642ee '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());
});

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

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

d973597657c05dfc9f24b5259e680b04classspath = __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) .'');
}
// private
public  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实现消息队列

php实现消息队列类实例分享

什么是消息队列?在Linux中使用消息队列

以上是PHP訊息佇列詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn