2 Commits
Author SHA1 Message Date
wonder 0628c6892a 🔄Update: 接收一条信息 2025-11-13 23:42:13 +08:00
wonder d0ef5e2950 🔄Update: 发送一条消息 2025-11-13 23:31:13 +08:00
2 changed files with 5 additions and 32 deletions
+1 -15
View File
@@ -7,7 +7,6 @@ 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 {
@@ -23,20 +22,7 @@ public class Recv {
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);
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});
}
}
+4 -17
View File
@@ -5,7 +5,6 @@ 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 {
@@ -14,23 +13,11 @@ public class Send {
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 channel = connection.createChannel()){
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;
}
}
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
} catch (IOException | TimeoutException e) {
throw new RuntimeException(e);
}