阅读量:0
要在PHP中使用AMQP实现消息队列,首先需要安装一个AMQP扩展,如php-amqplib/php-amqplib
。以下是一个简单的示例,展示了如何使用AMQP实现生产者(发送者)和消费者(接收者)之间的通信。
- 安装php-amqplib/php-amqplib库:
composer require php-amqplib/php-amqplib
- 创建一个生产者(sender.php):
<?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); $message = new AMQPMessage('Hello World!'); $channel->basic_publish($message, '', 'hello'); echo " [x] Sent 'Hello World!'\n"; $channel->close(); $connection->close();
- 创建一个消费者(receiver.php):
<?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 ($channel->is_consuming()) { $channel->wait(); } $channel->close(); $connection->close();
- 分别运行生产者和消费者脚本:
php sender.php php receiver.php
在这个例子中,生产者将发送一条消息到名为hello
的队列,而消费者将从该队列接收并处理消息。这就是如何使用AMQP实现PHP中的消息队列。