要使用php的amqplib庫實(shí)現(xiàn)消息持久化,你需要在創(chuàng)建隊(duì)列和交換機(jī)時(shí)設(shè)置一些參數(shù)。以下是一個(gè)簡單的示例:
composer require php-amqplib/php-amqplib
publisher.php
的文件,用于發(fā)送持久化消息:<?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();
// 創(chuàng)建一個(gè)持久化的交換機(jī)
$channel->exchange_declare('persistent_exchange', 'direct', false, true, false);
// 創(chuàng)建一個(gè)持久化的隊(duì)列
$channel->queue_declare('persistent_queue', false, true, false, false);
// 將隊(duì)列綁定到交換機(jī)
$channel->queue_bind('persistent_queue', 'persistent_exchange');
// 創(chuàng)建一個(gè)持久化的消息
$msg = new AMQPMessage('Hello, persistent message!', array('delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
// 發(fā)送消息到交換機(jī)
$channel->basic_publish($msg, 'persistent_exchange');
echo "Sent persistent message!\n";
$channel->close();
$connection->close();
consumer.php
的文件,用于接收持久化消息:<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
// 創(chuàng)建一個(gè)持久化的隊(duì)列
$channel->queue_declare('persistent_queue', false, true, false, false);
echo "Waiting for messages...\n";
$callback = function ($msg) {
echo 'Received: ', $msg->body, "\n";
};
// 消費(fèi)持久化消息
$channel->basic_consume('persistent_queue', '', false, true, false, false, $callback);
while ($channel->is_consuming()) {
$channel->wait();
}
$channel->close();
$connection->close();
publisher.php
文件發(fā)送持久化消息:php publisher.php
consumer.php
文件接收持久化消息:php consumer.php
這樣,你就成功地使用php的amqplib庫實(shí)現(xiàn)了消息持久化。當(dāng)RabbitMQ服務(wù)器重啟后,持久化的消息仍然會(huì)存在。