From f03568cc8ed3a380615555dec9087ab355f97850 Mon Sep 17 00:00:00 2001 From: Wonder Date: Fri, 14 Nov 2025 09:43:34 +0800 Subject: [PATCH] =?UTF-8?q?=20=F0=9F=94=84Update:=20=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E5=B9=B6=E5=AE=8C=E6=88=90=E4=BB=BB=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/cn/hezhaohui/mq/Recv.java | 42 +++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/cn/hezhaohui/mq/Recv.java diff --git a/src/main/java/cn/hezhaohui/mq/Recv.java b/src/main/java/cn/hezhaohui/mq/Recv.java new file mode 100644 index 0000000..f7f0920 --- /dev/null +++ b/src/main/java/cn/hezhaohui/mq/Recv.java @@ -0,0 +1,42 @@ +package cn.hezhaohui.mq; + +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; +import com.rabbitmq.client.DeliverCallback; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Random; +import java.util.concurrent.TimeoutException; + +public class Recv { + private final static String QUEUE_NAME = "hello"; + + public static void main(String[] args) throws IOException, TimeoutException { + ConnectionFactory connectionFactory = new ConnectionFactory(); + Connection connection = connectionFactory.newConnection(); + Channel channel = connection.createChannel(); + + System.out.println(" [*] Waiting for message"); + + DeliverCallback deliverCallback = (consumerTag, delivery) -> { + String message = new String(delivery.getBody(), StandardCharsets.UTF_8); + System.out.println(" [x] Received '" + message + "'"); + try { + dowork(message); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } finally { + System.out.println(" [x] Done"); + } + }; + boolean autoAck = true; + channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, consumerTag -> {}); + } + + private static void dowork(String task) throws InterruptedException { + System.out.println(" [Working] " + task); + Thread.sleep(1000); + } +}