简单实现一个mq确认消息不丢失的Java代码
时间: 2023-02-19 22:32:11 浏览: 161
JAVA发送MQ信息
4星 · 用户满意度95%
以下是一个简单的mq确认消息不丢失的Java代码示例:
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
//创建连接
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//声明队列
String queueName = "myQueue";
channel.queueDeclare(queueName, false, false, false, null);
//设置消费者
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");
//确认消息
channel.basicAck(envelope.getDeliveryTag(), false);
}
};
//开始消费
channel.basicConsume(queueName, false, consumer);
阅读全文