RabbitMQ 教程

ReturnListener1.java

import com.rabbitmq.client.*;
      import java.io.IOException;

/**
 * 使用 channel.addReturnListener() 添加 ReturnListener 监听器,监听
 * 没有成功路由给队列的消息。
 * @author hxstrive.com
 * @date 2022年2月17日13:59:29
 */
public class ReturnListener1 {
   private static final String EXCHANGE_NAME = "exchange_" +
         ReturnListener1.class.getSimpleName();

   /**
    * 发送消息
    */
   private void sender() throws Exception {
      // 创建连接
      ConnectionFactory factory = new ConnectionFactory();
      factory.setHost("127.0.0.1");
      factory.setPort(5672);
      Connection connection = factory.newConnection();

      // 创建通道
      Channel channel = connection.createChannel();
      channel.exchangeDeclare(EXCHANGE_NAME, "topic");
      channel.addReturnListener(new ReturnListener() {
         public void handleReturn(int replyCode, String replyText, String exchange,
               String routingKey, AMQP.BasicProperties properties,
               byte[] body) throws IOException {
            System.out.println("<< " + new String(body));
         }
      });

      // 发送消息
      System.out.println("[Send] Sending Message...");
      byte[] msg = ("hello wrold " + System.currentTimeMillis()).getBytes();
      channel.basicPublish(EXCHANGE_NAME, "www.hxstrive.com",
            true, MessageProperties.PERSISTENT_TEXT_PLAIN, msg);
      System.out.println("[Send] msg = " + new String(msg));

      Thread.sleep(Long.MAX_VALUE);
      // 释放资源
      channel.close();
      connection.close();
   }

   public static void main(String[] args) throws Exception {
      ReturnListener1 demo = new ReturnListener1();
      demo.sender();
   }

}
说说我的看法
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
公众号