RabbitMQ 教程

RejectMessage1.java

/**
 * 消费消息,拒绝消息(拒绝后自动重新放入到队列)
 * @author hxstrive.com
 * @date 2022年2月17日13:59:29
 */
public class RejectMessage1 {
   private static final String EXCHANGE_NAME = "exchange_" +
         RejectMessage1.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");

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

      // 释放资源
      channel.close();
      connection.close();
   }

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

      // 创建通道
      final Channel channel = connection.createChannel();
      channel.exchangeDeclare(EXCHANGE_NAME, "topic");

      // 绑定exchange与queue
      final String queueName = channel.queueDeclare().getQueue();
      channel.queueBind(queueName, EXCHANGE_NAME, "*.hxstrive.com");
      System.out.println("[Receive] Waiting Message...");

      // 消费消息
      channel.basicConsume(queueName, false, new DefaultConsumer(channel){
         @Override
         public void handleDelivery(String consumerTag, Envelope envelope,
               AMQP.BasicProperties properties, byte[] body) throws IOException {
            // 打印消息
            System.out.println("[Receive] message = " + new String(body));

            // 拒绝消息
            try {
               Thread.sleep(1000);
            } catch (Exception e) {}
            channel.basicReject(envelope.getDeliveryTag(), true);
         }
      });
   }

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

}
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号