RabbitMq初探——消息持久化
消息持久化
前言
通过上一节,我们知道,有消息确认机制,保证了当消费者进程挂掉后,消息的不丢失。
但是如果rabbitmq挂掉呢?它的队列和消息都会丢失的。为了保证消息在rabbitmq挂掉重启后不丢失,
我们需要用到rabbitmq的持久化机制。
开启持久化功能
1. 首先保证queue的持久化,在publisher和consumer声明queue时,开启持久化功能。本章例子可以通过下面代码开启
//函数第三个参数置为true,代表开启队列的持久化 $channel->queue_declare('durable_queue', false, true, false, false);
2. 其次保证message的持久化,在publisher传递消息前开启消息的持久化功能。
$msg = new AMQPMessage($data, array('delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
代码
sender.php
<?php /** * sender.php * Created by PhpStorm. * User: wangdaxi * Date: 2017/10/18 * Time: 14:26 */ require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Message\AMQPMessage; $connection = new AMQPStreamConnection('127.0.0.1', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('durable_queue', false, true, false, false); $data = implode(" ", array_slice($argv, 1)); empty($data) && $data = "Hello World!"; $msg = new AMQPMessage($data, array('delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT)); $channel->basic_publish($msg, '', 'durable_queue'); echo " [x] Sent '$data'\n"; //close the channel and connection; $channel->close(); $connection->close();
receive.php
<?php /** * receive.php * Created by PhpStorm. * User: wangdaxi * Date: 2017/10/18 * Time: 14:34 */ require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPStreamConnection; $connection = new AMQPStreamConnection('127.0.0.1', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('durable_queue', false, true, false, false); echo ' [*] Waiting for messages. To exit press CTRL+C', "\n"; $callback = function($msg) { echo "[x] Received ", $msg->body, "\n"; sleep(substr_count($msg->body, '.')); echo "[x] Done\n"; //消息确认 $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']); }; $channel->basic_consume('durable_queue', '', false, false, false, false, $callback); while(count($channel->callbacks)) { $channel->wait(); }
测试
1. php sender.php 这里开启了队列,并且发送了一条消息‘hello world’
2. sudo rabbitmqctl stop_app 关闭服务
3. sudo rabbitmqctl start_app 开启服务
4. php receive.php 开启消费者进程,发现能从队列【durable_queue】接收到消息。
以上。