php如何使用rabbitmq客户端

发布者: xiaozhimn

写一个简单的“Hello World”测试程序

1)安装PHP amqplib客户端库 composer require php-amqplib/php-amqplib
(2)构建一个发送消息的文件send.php,即“P”,发布消息

composer 如果查看安装进度怎么办?

composer require -vvv php-amqplib/php-amqplib

composer安装过慢怎么办?

在composer.json 中增加:
 "repositories": {
        "packagist": {
            "type": "composer",
            "url": "https://mirrors.aliyun.com/composer/"
        }
    }
使用阿里云镜像即可体验速度的提升

生产者demo

//引用所需文件
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
//建立一个连接通道,声明一个可以发送消息的队列hello
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare('hello', false, false, false, false);

//定义一个消息,消息内容为Hello World!
$msg = new AMQPMessage('Hello World!');
$channel->basic_publish($msg, '', 'hello');

//发送完成后打印消息告诉发布消息的人:发送成功
echo " [x] Sent 'Hello World!'\n";
//关闭连接
$channel->close();
$connection->close();

消费者demo

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

//在接收消息的时候调用$callback函数
$channel->basic_consume('hello', '', false, true, false, false, $callback);

while(count($channel->callbacks)) {
    $channel->wait();
}
0赞