你或許在思考數據分發、無阻塞做業或者消息推送。或者你想要進行發佈/訂閱,異步任務,工做隊列。全部的這些模式,都是消息隊列的一部分。
wget https://www.rabbitmq.com/releases/rabbitmq-server/v3.6.8/rabbitmq-server-3.6.8-1.el6.noarch.rpm
獲取rpm ,安裝的時候會發現缺乏依賴php
安裝依賴erlangshell
wget https://packages.erlang-solutions.com/erlang-solutions-1.0-1.noarch.rpm rpm -Uvh erlang-solutions-1.0-1.noarch.rpm yum install erlang
注意不要用epel的源直接yum安裝,epel源的erlang版本過低
安裝依賴socat併發
yum install socat
最後異步
rpm -Uvh rabbitmq-server-3.6.8-1.el6.noarch.rpm
{ "require": { "php-amqplib/php-amqplib": "2.6.*" } }
comoser install
//send.php require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Message\AMQPMessage; $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('hello', false, false, false, false); $msg = new AMQPMessage('Hello World!'); $channel->basic_publish($msg, '', 'hello'); //發送一個消息到hello頻道 echo " [x] Sent 'Hello World!'\n"; $channel->close(); $connection->close();
//receive.php require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPStreamConnection; $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('hello', false, false, false, false); echo ' [*] Waiting for messages. To exit press CTRL+C', "\n"; $callback = function($msg) { echo " [x] Received ", $msg->body, "\n"; }; //接收hello頻道的消息 $channel->basic_consume('hello', '', false, true, false, false, $callback); while(count($channel->callbacks)) { $channel->wait(); }
首先運行起來rabbmitMQ server高併發
service rabbmitmq-server start
掛起receive.php接收消息處理ui
php receive.php
發送消息spa
##另起一個窗口執行 php send.php
以上代碼就構建了一個簡單的消息隊列命令行
消息從send.php 生產(p) 進入隊列 交由 消費者(c)code
注意:當關閉了命令行窗口receive.php 進程將會結束,這個時候就須要藉助
supservisor 來將receive.php 腳本後臺運行。這部分代碼能夠改寫應用做簡單的異步隊列任務的場景,但到了高併發高可用需求下就要進行額外的一些處理。在以後的文章中我會講到rabbmitMQ的競爭消費模式和superverisor的用法。server