1、RabbitMQ結構php
先用phpinfo()查看php版本信息,linux
最後根據上面的信息去下載相應的amqp版本:http://pecl.php.net/package/amqpweb
據上面信息咱們的是64位線程安全版本apache
加壓後:安全
將php_amqp.dll複製到php/ext,同時在php.ini中添加以下代碼:服務器
[amqp] php7
extension=php_amqp.dll ide
而後將rabbitmq.4.dll複製到php根目錄C:/xampp/php/,同時修改apache配置文件httpd.conf,添加以下代碼:測試
# rabbitmqspa
LoadFile "C:/xampp/php/rabbitmq.4.dll"
最後重啓看看是否已經加載了amqp模塊:
3、若是要在cli模式下測試運行rabbitmq,要配置cli模式的php.ini文件
一、查看運行模式下的php.ini的位置
(1)查看命令行模式下加載的php配置文件
php -i|findstr .ini (window)
php -i|grep .ini (linux)
一般爲php安裝目錄下的php.ini文件
如:D:\soft\wamp64\bin\php\php7.2.14\php.ini
(2)查看web模式下php加載的配置文件
phpinfo();
一般爲apache目錄下的php.ini文件
如:D:\soft\wamp64\bin\apache\apache2.4.37\bin\php.ini
二、配置D:\soft\wamp64\bin\php\php7.2.14\php.ini,在文件末尾加入
[amqp]
extension=php_amqp.dll
保存便可
4、php測試rabbitmq
一、發送者(publisher):rabbit_publisher.php
建立鏈接-->建立channel-->建立交換機對象-->建立隊列-->發送消息
<?php $exchangeName = 'demo'; $queueName = 'hello'; $routeKey = 'hello'; $message = 'Hello World!'; $connection = new AMQPConnection( array('host' => '127.0.0.1', 'port' => '5672', 'vhost' => '/', 'login' => 'guest', 'password' => 'guest') ); $connection->connect() or die("Cannot connect to the broker!\n"); try { $channel = new AMQPChannel($connection); $exchange = new AMQPExchange($channel); $exchange->setName($exchangeName); $queue = new AMQPQueue($channel); $queue->setName($queueName); $exchange->publish($message, $routeKey); var_dump("[x] Sent 'Hello World!'"); } catch (AMQPConnectionException $e) { var_dump($e); exit(); } $connection->disconnect(); ?>
二、消費者(consumer):rabbit_consumer.php
建立鏈接-->建立channel-->建立交換機-->建立隊列-->綁定交換機/隊列/路由鍵-->接收消息
<?php $exchangeName = 'demo'; $queueName = 'hello'; $routeKey = 'hello'; $connection = new AMQPConnection(array('host' => '127.0.0.1', 'port' => '5672', 'vhost' => '/', 'login' => 'guest', 'password' => 'guest')); $connection->connect() or die("Cannot connect to the broker!\n"); $channel = new AMQPChannel($connection); $exchange = new AMQPExchange($channel); $exchange->setName($exchangeName); $exchange->setType(AMQP_EX_TYPE_DIRECT); $exchange->declareExchange(); // AMQP 1.2.0 由 declare() 改成 declareExchange(); $queue = new AMQPQueue($channel); $queue->setName($queueName); $queue->declareQueue();//AMQP 1.2.0 由 declare() 改成 declareQueue(); $queue->bind($exchangeName, $routeKey); var_dump('[*] Waiting for messages. To exit press CTRL+C'); while (TRUE) { $queue->consume('callback'); } function callback($envelope, $queue) { $msg = $envelope->getBody(); var_dump(" [x] Received:" . $msg); $queue->nack($envelope->getDeliveryTag()); } $connection->disconnect(); ?>
三、以管理者的身份運行RabbitMQ Command,啓動mq:net start rabbitmq。切換到項目文件目錄,執行消費者文件
四、從新開啓一個命令行窗口,一樣切換到項目文件目錄,執行生產者文件
會看到每執行一次生產者文件,消費者那裏都會受到生產者發送的消息:Hello World!