RabbitMQ是一款消息隊列中間件。他提供了幾乎覆蓋全部語言的SDK與文檔,簡直強大的不的了。要詳細的去了解學習RabbitMQ,我建議仍是看官方文檔吧。 http://www.rabbitmq.com/getst...
消息隊列有如下幾個基本用途php
消息隊列的這幾個用途我會在後續的文章以真實案例去表述
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel ();
與連接一個數據庫概念差很少html
$channel->queue_declare ('hello');
建立多個隊列與建立多個數據庫同樣,hello則是隊列名數據庫
$message = new AMQPMessage('Hello World!');
$channel->basic_publish ($message, '', 'hello');
hello 是上面建立的隊列聲明segmentfault
$channel->close (); $connection->close ();
釋放資源多線程
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel ();
與連接一個數據庫概念差很少架構
$channel->queue_declare ('hello');
建立多個隊列與建立多個數據庫同樣,hello則是隊列名異步
$channel->basic_consume ('hello', '', false, true, false, false, function ($msg) { echo ' [x] Received ', $msg->body, "\n"; });
經過回調函數處理消息隊列函數
while (count ($channel->callbacks)) { $channel->wait (); }
無消息時,掛起保持等待狀態學習
$channel->close (); $connection->close ();
釋放資源spa
完整的按鈕則是上面全部代碼的整理
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel (); $channel->queue_declare ('hello'); $message = new AMQPMessage('Hello World!'); $channel->basic_publish ($message, '', 'hello'); $channel->close (); $connection->close ();
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel (); $channel->queue_declare ('hello'); // basic_consume 方法第7個方法能夠直接傳入函數 $channel->basic_consume ('hello', '', false, true, false, false, function ($msg) { echo ' [x] Received ', $msg->body, "\n"; }); while (count ($channel->callbacks)) { $channel->wait (); } $channel->close (); $connection->close ();
php {生產者}.php php {消費者}.php
RabbitMQ支持多線程處理消息隊列,全部你能夠開啓多個消費者去執行消息隊列內的任務。你能夠像我這樣
若是你感受RabbitMQ這玩意還須要安裝啥的感受特麻煩,那你能夠看下個人Laravel隊列如何簡單的玩起來。
https://segmentfault.com/a/11...
感謝你看完我這篇文章,純手記的一篇文章,官方文檔對新手的理解形成不少的誤解,因此整理此文檔,儘可能避免新手「進」坑吧。對文章有什麼問題或疑問,歡迎在評論區留言。謝謝