簡介:php
內容:html
1nginx
1.1 docker 安裝 rabbitmq(前提是系統已安裝docker)docker
編寫docker-compose.yml文件內容json
version: '3' services: rabbitmq: # https://hub.docker.com/_/rabbitmq/ image: rabbitmq:3.7.7-management-alpine hostname: myrabbitmq ports: - "5672:5672" # mq port - "15672:15672" # admin port
啓動:bash
docker-compose up -d rabbitmq
顯示以下安裝成功:composer
1.2 也可經過 brew方式安裝 rabbitmqcurl
brew install rabbitmq
顯示以下安裝成功。php-fpm
如訪問 http://127.0.0.1:15672 未出現預期頁面,可能未啓動服務,執行以下命令啓動。ui
brew services start rabbitmq
訪問正常以下,默認帳號密碼爲: guest guest。
登陸後頁面。
2安裝官方php-amqp 擴展
未安裝php-amqp擴展,或者擴展安裝失敗,執行php代碼會出現以下提示。
安裝rabbitmq-c。
brew install rabbitmq-c
下載官方php-amqp 擴展。rabbitmq 是amqp協議的開源實現。
curl 'http://pecl.php.net/get/amqp-1.9.3.tgz' -o amqp-1.9.3.tgz
解壓下載包。進入源碼根目錄。執行以下命令。
phpize
--with-librabbitmq-dir這個須要修改成你環境rabbitmq-c的安裝地址,brew 安裝成功是最後會出現此安裝目錄信息。
--with-php-config這個配置爲你環境的php-config地址
./configure --with-php-config=/usr/local/Cellar/php@5.6/5.6.39/bin/php-config -with-amqp --with-librabbitmq-dir=/usr/local/Cellar/rabbitmq-c/0.9.0
make && make install
make成功,會出現以下信息。
添加.so文件至php.ini文件。
重啓php-fpm nginx。
打印phpinfo()。顯示以下,則安裝成功。
3 官方樣例
https://www.rabbitmq.com/tutorials/tutorial-one-php.html
例子:發送10次hello world
composer.json
{ "require": { "php-amqplib/php-amqplib": ">=2.6.1" } }
引入包
composer install
編寫消費者代碼:
receive.php
<?php /** * Created by Afei. * User: feiwang * Date: 2019-08-15 * Time: 21:00 */ 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"; }; $channel->basic_consume('hello', '', false, true, false, false, $callback); while ($channel->is_consuming()) { $channel->wait(); } $channel->close(); $connection->close();
消息生產者代碼:
send.php
<?php /** * Created by Afei. * User: feiwang * Date: 2019-08-15 * Time: 20:55 */ 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); for ($i=0;$i<10;$i++){ $m = 'Hello World! time now:'.date("H:i:s",time())." ".$i; $msg = new AMQPMessage($m); $channel->basic_publish($msg, '', 'hello'); echo $m."\n"; } $channel->close(); $connection->close();
先執行 php receive.php
再執行 php send.php
效果: