如果想要让消息重启后仍然不丢失,那么需要将queue设置成 durable 为true , 并且发送消息的时候指明消息是要持久化得MessageProperties.PERSISTENT_TEXT_PLAIN
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes());
发送代码:
package com.rabbitmq.queue.durable;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.queue.ConnectionUtil;
/**
* @author: ZhangHouYing
* @date: 2018-09-11 20:20
*/
public class Send {
private final static String QUEUE_NAME = "test_queue_durable";
public static void main(String[] argv) throws Exception {
// 获取到连接以及mq通道
Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
//发送50条消息
for (int i = 0; i < 50; i++) {
// 消息内容
String message = "durable_" + i;
channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
channel.close();
connection.close();
}
}
接收的时候默认服务器会一次性把50条都给客户端,如果要指定每次处理条数可以通过
channel.basicQos(1); //告诉服务器每次我们只要一条
autoAck为false告诉服务器我们要确认收到消息才算数,于是我们拿到一条,服务器就会把那条放入Unacked 目录中
只有当我们把确认消息回传给服务器,才算是结束
channel.basicAck(envelope.getDeliveryTag(), false);//消息确认收到了,
channel.basicConsume(QUEUE_NAME, false, consumer);//需要客户端确认才算是
接收代码:
package com.rabbitmq.queue.durable;
import com.rabbitmq.client.*;
import com.rabbitmq.queue.ConnectionUtil;
import java.io.IOException;
/**
* @author: ZhangHouYing
* @date: 2018-09-11 20:21
*/
public class Recv {
private final static String QUEUE_NAME = "test_queue_durable";
public static void main(String[] argv) throws Exception {
// 获取到连接以及mq通道
Connection connection = ConnectionUtil.getConnection();
final Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
// 同一时刻服务器只会发一条消息给消费者
//channel.basicQos(1);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
// 创建队列消费者
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println(message);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
channel.basicAck(envelope.getDeliveryTag(), false);
}
};
channel.basicConsume(QUEUE_NAME, false, consumer);
}
}