php rabbitMQ使用教程

  • 慢点
  • 2019-08-09 16:01:05
  • 188已阅读

php rabbitMQ使用教程

一、rabbitMQ服务端 安装

https://jingyan.baidu.com/article/e4d08ffd9ec61c0fd2f60d1f.html


二、php_amqp扩展包安装

php 扩展包:http://pecl.php.net/package/amqp/1.9.3/windows

extension=php_amqp.dll(D:\phpStudy\PHPTutorial\php\php-7.0.12-nts\ext

rabbitmq.4.dll(D:\phpStudy\PHPTutorial\php\php-7.0.12-nts

三、composer 安装

https://getcomposer.org/download/

使用国内源

切换源

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ //

OR composer config -g repo.packagist composer https://mirrors.huaweicloud.com/repository/php/


也可以手工在composer.json中添加如下内容:

"repositories": {

"packagist": {

"type": "composer",

"url": "https://mirrors.aliyun.com/composer/"

}

}


四、composer安装代码包

代码包下载:

https://packagist.org/packages/php-amqplib/php-amqplib

composer require php-amqplib/php-amqplib



五、rabbitMQ web管理

https://blog.csdn.net/chenshourui/article/details/81203770


六、代码示例

\models\RabbitMQ

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";
};

$channel->basic_consume('hello', '', false, true, false, false, $callback);

while (count($channel->callbacks)) {
   $channel->wait();
}
$channel->close();
$connection->close();

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');

echo " [x] Sent 'Hello World!'\n";

$channel->close();
$connection->close();