Java使用RabbitMQ之消息确认(confirm模板)

  RabbitMQ生产者消息确认Confirm模式,分为普通模式、批量模式和异步模式,本次举例为普通模式。

源码:

 1 package org.study.confirm4;
 2 
 3 import com.rabbitmq.client.Channel;
 4 import com.rabbitmq.client.Connection;
 5 import org.junit.Test;
 6 import org.study.utils.ConnectionUtils;
 7 
 8 import java.io.IOException;
 9 import java.util.concurrent.TimeoutException;
10 
11 /**
12  * 生产者消息确认(confirm)
13  */
14 public class Sender {
15     public static final String QUEUE_NAME = "test_confirm_queue";
16 
17     @Test
18     public void send() throws IOException, TimeoutException, InterruptedException {
19         // 获取连接
20         Connection conn = ConnectionUtils.getConnection();
21         // 获取通道
22         Channel channel = conn.createChannel();
23         //创建队列
24         channel.queueDeclare(QUEUE_NAME, false, false, false, null);
25         //每个消费者发送确认消息前,只发送一条消息
26         channel.basicQos(1);
27         String msg = "hello rabbitmq!";
28 
29         //开启confirm模式
30         channel.confirmSelect();
31 
32         //发送消息
33         channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
34         System.out.println("[send] msg " + msg);
35 
36         //判断消息返回是否成功
37         if (channel.waitForConfirms()) {
38             System.out.println("发送成功!");
39         } else {
40             System.out.println("发送失败!");
41         }
42 
43         channel.close();
44         conn.close();
45     }
46 }

 

posted @ 2018-09-14 15:31  星瑞  阅读(674)  评论(0编辑  收藏  举报