Php使用RabbitMQ入门小demo
1.首先需要安装PHP使用的RabbitMQ 包:php-amqplib
composer require php-amqplib/php-amqplib
php必须安装拓展:php_sockets,不然会报错:
The requested PHP extension ext-sockets * is missing from your system. Install or enable PHP"s sockets extension.
2.建立服务端和客户端:
server.php
<?php// +----------------------------------------------------------------------
// | 蜜蜂到店
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.mifengdaodian.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: DB <m18108447675@gmail.com.com>
// +----------------------------------------------------------------------
// | Date Time: 2019/11/25 10:26
// +----------------------------------------------------------------------
// | Description: rabbitMQ服务端
// +----------------------------------------------------------------------
require_once __DIR__."/vendor/autoload.php";
use PhpAmqpLibConnectionAMQPStreamConnection; //引入数据流通道类
use PhpAmqpLibMessageAMQPMessage; //引入队列类
//连接主机
$connection = new AMQPStreamConnection("localhost", 5672, "guest", "guest");
//建立通道
$channel = $connection->channel();
//建立队列
$channel->queue_declare("hello", false, false, false, false);
//准备消息
$msg = new AMQPMessage("hello,我要发送的消息内容~~~".time());
//公布消息
$channel->basic_publish($msg, "", "hello");
//关闭通道
$channel->close();
//关闭链接
$connection->close();
客户端文件client.php
<?php// +----------------------------------------------------------------------
// | 蜜蜂到店
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.mifengdaodian.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: DB <m18108447675@gmail.com.com>
// +----------------------------------------------------------------------
// | Date Time: 2019/11/25 10:26
// +----------------------------------------------------------------------
// | Description: rabbitMQ客户端
// +----------------------------------------------------------------------
require_once __DIR__ . "/vendor/autoload.php";
use PhpAmqpLibConnectionAMQPStreamConnection; //引入队列流连接类
//连接主机
$connection = new AMQPStreamConnection("localhost", 5672, "guest", "guest");
//建立通道
$channel = $connection->channel();
//创建队列
$channel->queue_declare("hello", false, false, false, false);
//闭包回调函数
$callback = function ($msg) {
echo " [x] Received ", $msg->body, "
";
};
//消费队列消息
$channel->basic_consume("hello", "", false, true, false, false, $callback);
//等待消息
while ($channel->is_consuming()) {
$channel->wait();
}
3.执行client.php 然后执行server.php
在clent.php就能看见server.php队列消息了
以上是 Php使用RabbitMQ入门小demo 的全部内容, 来源链接: utcz.com/z/511146.html