假設你喜歡用PHP構建WEB應用,然後還有一些外圍的應用,包括移動終端APP,mobile web等,
由於mobile app等是非PHP語言所編寫如ObjectiveC、Java等,然後你想在這些用戶端應用程式之間共用某些基礎服務,
希望這些基礎服務以一種松耦合,高擴充性,高效能的方式來提供,那麼一個比較好的解決方案是使用跨平台的訊息中介軟體ActiveMQ。
對於PHP用戶端而言,要使用ActiveMQ,可以使用兩種方式,一種是rest方式(基於HTTP),一種是藉助Stomp:
http://en.wikipedia.org/wiki/Streaming_Text_Orientated_Messaging_Protocol
基於rest是無狀態的,而基於Stomp則要求保持串連(Stomp基於TCP協議)。
基於rest方式,可閱讀如下連結,本文不做詳解:
http://activemq.apache.org/rest.html
下面具體樣本PHP如何使用Stomp:
//send a message to the queue function sendMQ($data) { $link = openMQ(); foreach ($data as $pitem) { //使用 persistent message $result = stomp_send($link, $amq['queue'], $pitem, array("persistent" => "true")); if (FALSE === $result) { //do something } } } //receive message function receiveMQ() { $link = openMQ($queue); stomp_subscribe($link, $queue); while (1) { if (TRUE === stomp_has_frame($link)) { $frame = stomp_read_frame($link); if (FALSE !== $frame) { stomp_ack($link, $frame['headers']['message-id']); } else { //do something break; } } else { break; } } stomp_unsubscribe($link, $queue); stomp_close($link); } //connection ActiveMQ function openMQ(&$queue=FALSE) { $amq = array( 'url' => 'tcp://127.0.0.1:61613', 'id' => 'xxx', 'pswd' => 'xxx', 'queue' => '/queue/mytest', 'enable' => TRUE ); $link = stomp_connect($amq['url'], $amq['id'], $amq['pswd']); if (!$link) { die("Can't connect MQ !!"); } else { return $link; } }
注意Stomp讀取方需要調整prefetchSize,如下:
stomp_subscribe($link, $queue, array("activemq.prefetchSize" => 1000));
否則可能會發現讀取訊息非常緩慢。prefetchSize欄位含義如下:
Specifies the maximum number of pending messages that will be dispatched to the client.
Once this maximum is reached no more messages are dispatched until the client acknowledges a message.
Set to 1 for very fair distribution of messages across consumers where processing messages can be slow.
詳細原因可仔細閱讀:ActiveMQ In Action 一書。
參考資料:
Apache ActiveMQ - Enterprise messaging in actionstomp進階說明-prefetchSize、ack header
ActiveMQ extensions to Stomp
stomping-with-php-intergration-with-activemq