PHP使用enqueue/amqp-lib实现rabbitmq任务处理
Sure, here's an example of how to use PHP and the Enqueue/AMQP-Lib library to implement task processing with RabbitMQ:
1. Install Enqueue/AMQP-Lib:
Bash
composer require enqueue/amqp-lib
2. Create a Worker Script:
PHP
<?php
require __DIR__ . '/vendor/autoload.php';
use Enqueue\AMQP\AMQPConnectionFactory;
use Enqueue\AMQP\Queue\QueueConsumer;
use Enqueue\AMQP\Queue\QueueSubscriber;
$connectionFactory = new AMQPConnectionFactory('amqp://localhost');
$connection = $connectionFactory->create();
$consumer = new QueueConsumer($connection, 'your-queue-name');
$subscriber = new QueueSubscriber($consumer);
$subscriber->subscribe(function ($message) {
// Process the message here
echo "Received message: " . $message->getBody() . "\n";
// Acknowledge the message to indicate successful processing
$message->acknowledge();
});
$subscriber->loop();
3. Create a Task Publisher Script:
PHP
<?php
require __DIR__ . '/vendor/autoload.php';
use Enqueue\AMQP\AMQPConnectionFactory;
use Enqueue\AMQP\Queue\QueueProducer;
$connectionFactory = new AMQPConnectionFactory('amqp://localhost');
$connection = $connectionFactory->create();
$producer = new QueueProducer($connection, 'your-queue-name');
$message = new \AMQP\Message('This is a task message');
$producer->send($message);
echo "Task message sent.\n";
Explanation:
Worker Script:
AMQPConnectionFactory
and create()
methods.QueueConsumer
object, which listens for messages on the specified queue (your-queue-name
).QueueSubscriber
object using the QueueConsumer
.subscribe()
to be executed when a message is received.
$message
object, containing the message payload.$message->getBody()
.$message->acknowledge()
.subscriber->loop()
, which continuously monitors the queue for incoming messages and triggers the callback function accordingly.Task Publisher Script:
AMQPConnectionFactory
and create()
methods.QueueProducer
object, which sends messages to the specified queue (your-queue-name
).\AMQP\Message
object, containing the task message payload.producer->send($message)
.Remember:
your-queue-name
with the actual name of your queue.