2 Commits
Author SHA1 Message Date
wonder f03568cc8e 🔄Update: 获取并完成任务 2025-11-14 09:43:34 +08:00
wonder d744cf8d4e 🔄Update: 任务队列 2025-11-14 09:38:48 +08:00
2 changed files with 80 additions and 0 deletions
+42
View File
@@ -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);
}
}
+38
View File
@@ -0,0 +1,38 @@
package cn.hezhaohui.mq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) {
ConnectionFactory connectionFactory = new ConnectionFactory();
try (Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
Scanner scanner = new Scanner(System.in)){
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" === Now you can send message ===");
while (true) {
System.out.println("[Send]:");
String message = scanner.nextLine();
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
if ("exit".equalsIgnoreCase(message)) {
System.out.println(" [x] Bye");
break;
}
}
} catch (IOException | TimeoutException e) {
throw new RuntimeException(e);
}
}
}