1. 程式人生 > >PHP高階程式設計之訊息佇列

PHP高階程式設計之訊息佇列

轉載:https://blog.csdn.net/luyaran/article/details/53034382

1. 什麼是訊息佇列

訊息佇列(英語:Message queue)是一種程序間通訊或同一程序的不同執行緒間的通訊方式

2. 為什麼使用訊息佇列

訊息佇列技術是分散式應用間交換資訊的一種技術。訊息佇列可駐留在記憶體或磁碟上,佇列儲存訊息直到它們被應用程式讀出。通過訊息佇列,應用程式可獨立地執行,它們不需要知道彼此的位置、或在繼續執行前不需要等待接收程式接收此訊息。

3. 什麼場合使用訊息佇列

你首先需要弄清楚,訊息佇列與遠端過程呼叫的區別,在很多讀者諮詢我的時候,我發現他們需要的是RPC(遠端過程呼叫),而不是訊息佇列。

訊息佇列有同步或非同步實現方式,通常我們採用非同步方式使用訊息佇列,遠端過程呼叫多采用同步方式。

MQ與RPC有什麼不同? MQ通常傳遞無規則協議,這個協議由使用者定義並且實現儲存轉發;而RPC通常是專用協議,呼叫過程返回結果。

4. 什麼時候使用訊息佇列

同步需求,遠端過程呼叫(PRC)更適合你。

非同步需求,訊息佇列更適合你。

目前很多訊息佇列軟體同時支援RPC功能,很多RPC系統也能非同步呼叫。

訊息佇列用來實現下列需求
  1. 儲存轉發

  2. 分散式事務

  3. 釋出訂閱

  4. 基於內容的路由

  5. 點對點連線

5. 誰負責處理訊息佇列

通常的做法,如果小的專案團隊可以有一個人實現,包括訊息的推送,接收處理。如果大型團隊,通常是定義好訊息協議,然後各自開發各自的部分,例如一個團隊負責寫推送協議部分,另一個團隊負責寫接收與處理部分。

那麼為什麼我們不講訊息佇列框架化呢?

框架化有幾個好處:
  1. 開發者不用學習訊息佇列介面
  2. 開發者不需要關心訊息推送與接收
  3. 開發者通過統一的API推送訊息
  4. 開發者的重點是實現業務邏輯功能

6. 怎麼實現訊息佇列框架

下面是作者開發的一個SOA框架,該框架提供了三種介面,分別是SOAP,RESTful,AMQP(RabbitMQ),理解了該框架思想,你很容易進一步擴充套件,例如增加XML-RPC, ZeroMQ等等支援。

本文只講訊息佇列框架部分。

6.1. 守護程序

訊息佇列框架是本地應用程式(命令列程式),我們為了讓他在後臺執行,需要實現守護程序。

每個例項處理一組佇列,例項化需要提供三個引數,$queueName = '佇列名', $exchangeName = '交換名', $routeKey = '路由'

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

守護程序需要使用root使用者執行,執行後會切換到普通使用者,同時建立程序ID檔案,以便程序停止的時候使用。

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":["[email protected]","Hello"," TestHelloWorld",null]}			
			

使用json格式是考慮到通用性,這樣推送端可以使用任何語言。如果不考慮相容,建議使用二進位制序列化,例如msgpack效率更好。

6.3. 訊息佇列處理

訊息佇列處理核心程式碼

所以訊息的處理在下面一段程式碼中進行

$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. 測試

			
<?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=newAMQPChannel(channel = new AMQPChannel(connection);
exchange=newAMQPExchange(exchange = new AMQPExchange(channel);
KaTeX parse error: Expected 'EOF', got '&' at position 10: exchange-&̲gt;setName(exchangeName);
queue=newAMQPQueue(queue = new AMQPQueue(channel);
KaTeX parse error: Expected 'EOF', got '&' at position 7: queue-&̲gt;setName(queueName);
$queue->setFlags(AMQP_DURABLE);
$queue->declareQueue();

$msg = array(
‘Namespace’=>‘namespace’,
“Class”=>“Email”,
“Method”=>“smtp”,
“Param” => array(
$mail, $subject, $message, null
)
);

KaTeX parse error: Expected 'EOF', got '&' at position 10: exchange-&̲gt;publish(json…msg), routeKey);printf(&quot;[x]SentrouteKey); printf(&quot;[x] Sent %s \r\n&quot;, json_encode(msg));

$connection->disconnect();

		</span></strong></pre>

這裡只給出了少量測試與演示程式,如有疑問請到瀆者群,或者公眾號詢問。

7. 多執行緒

上面訊息佇列 核心程式碼如下

		
$this->queue->consume(function($envelope, $queue) {	
	$msg = $envelope->getBody();
	$result = $this->loader($msg);
	$queue->ack($envelope->getDeliveryTag());
});
	</span></strong></pre>

這段程式碼生產環境使用了半年,發現效率比較低。有些業務場入隊非常快,但處理起來所花的時間就比較長,容易出現佇列堆積現象。

增加多執行緒可能更有效利用硬體資源,提高業務處理能力。程式碼如下

		
<?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-&gt;classspath = __DIR__.'/../queue';
	$this-&gt;msg = $msg;
	$this-&gt;logging = $logging;
	$this-&gt;queue = $queue;
}
public function run() {
	$speed = microtime(true);
	$result = $this-&gt;loader($this-&gt;msg);
	$this-&gt;logging-&gt;debug('Result: '. $result.' ');
	$this-&gt;logging-&gt;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-&gt;classspath.'/'.$this-&gt;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-&gt;$method();
					$result = json_encode($tmp);
					$this-&gt;logging-&gt;info($class.'-&gt;'.$method.'()');
				}else{
					$tmp = call_user_func_array(array($obj, $method), $param);
					$result = (json_encode($tmp));
					$this-&gt;logging-&gt;info($class.'-&gt;'.$method.'("'.implode('","', $param).'")');
				}
			}else{
				$this-&gt;logging-&gt;error('Object '. $class. '-&gt;' . $method. ' is not exist.');
			}
		}else{
			$msg = sprintf("Object is not exist. (%s)", $class);
			$this-&gt;logging-&gt;error($msg);
		}
	}else{
		$msg = sprintf("Cannot loading interface! (%s)", $classspath);
		$this-&gt;logging-&gt;error($msg);
	}
	return $result;
}

}

class RabbitMQ {

const loop = 10;

protected $queue;
protected $pool;

public function __construct($queueName = '', $exchangeName = '', $routeKey = '') {

	$this-&gt;config = new \framework\Config('rabbitmq.ini');
	$this-&gt;logfile = __DIR__.'/../log/rabbitmq.%s.log';
	$this-&gt;logqueue = __DIR__.'/../log/queue.%s.log';
	$this-&gt;logging = new \framework\log\Logging($this-&gt;logfile, $debug=true);

 //.H:i:s

	$this-&gt;queueName	= $queueName;
	$this-&gt;exchangeName	= $exchangeName;
	$this-&gt;routeKey		= $routeKey; 

	$this-&gt;pool = new \Pool($this-&gt;config-&gt;get('pool')['thread']);

}
public function main(){
	
	$connection = new \AMQPConnection($this-&gt;config-&gt;get('rabbitmq'));
	try {
		$connection-&gt;connect();
		if (!$connection-&gt;isConnected()) {
			$this-&gt;logging-&gt;exception("Cannot connect to the broker!"

.PHP_EOL);
}
KaTeX parse error: Expected 'EOF', got '&' at position 6: this-&̲gt;channel = ne…connection);
KaTeX parse error: Expected 'EOF', got '&' at position 6: this-&̲gt;exchange = n…this->channel);
KaTeX parse error: Expected 'EOF', got '&' at position 6: this-&̲gt;exchange-&gt…this->exchangeName);
$this->exchange->setType(AMQP_EX_TYPE_DIRECT); //direct型別
$this->exchange->setFlags(AMQP_DURABLE); //持久�?
$this->exchange->declareExchange();
KaTeX parse error: Expected 'EOF', got '&' at position 6: this-&̲gt;queue = new …this->channel);
KaTeX parse error: Expected 'EOF', got '&' at position 6: this-&̲gt;queue-&gt;se…this->queueName);
$this->queue->setFlags(AMQP_DURABLE); //持久�?
$this->queue->declareQueue();

		$this-&gt;queue-&gt;bind($this-&gt;exchangeName, $this-&gt;routeKey);

		$this-&gt;queue-&gt;consume(function($envelope, $queue) {
			$msg = $envelope-&gt;getBody();
			$this-&gt;logging-&gt;debug('Protocol: '.$msg.' ');
			//$result = $this-&gt;loader($msg);
			$this-&gt;pool-&gt;submit(new RabbitThread($this-&gt;queueName, 

new \framework\log\Logging($this->logqueue, $debug=true), $msg));
KaTeX parse error: Expected 'EOF', got '&' at position 7: queue-&̲gt;ack(envelope->getDeliveryTag());
});
$this->channel->qos(0,1);
}
catch(\AMQPConnectionException $e){
KaTeX parse error: Expected 'EOF', got '&' at position 6: this-&̲gt;logging-&gt;…e->__toString());
}
catch(\Exception $e){
KaTeX parse error: Expected 'EOF', got '&' at position 6: this-&̲gt;logging-&gt;…e->__toString());
$connection->disconnect();
KaTeX parse error: Expected 'EOF', got '&' at position 6: this-&̲gt;pool-&gt;shu…tag, $msg){
KaTeX parse error: Expected 'EOF', got '&' at position 6: this-&̲gt;logging-&gt;…msg);
throw new \Exception(tag.:.tag.&#x27;: &#x27;.msg);
}

public function __destruct() {
}	

}

	</span></strong></pre>
        </div>
            </div>