我试图了解带有发送方和接收方程序的RabbitMQ服务器。现在,当发送方发送单个消息并且接收方将收到相同的消息时,整个设置运行良好。
然而,当我发送两条消息(通过运行发送两次)并运行接收程序两次时,我只得到第一条消息。
发件人
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
String message = "He12!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println("Sent "+message);
channel.close();
connection.close();
接收机
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, consumer);
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
/*channel.basicCancel(consumer.getConsumerTag()); */
String message;
if (delivery != null) {
message = new String(delivery.getBody());
System.out.println("Reciever .."+message);
}
channel.close();
connection.close();
答案 0 :(得分:1)
当我使用no_Ack = false修改Receiver并调用BasicAck时,问题解决了。感谢@robthewolf和@Card(推特)提供帮助。
PFB修改后的接收器。
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, false, consumer);
QueueingConsumer.Delivery delivery = consumer.nextDelivery(10);
/*channel.basicCancel(consumer.getConsumerTag()); */
String message = null;
if (delivery != null) {
message = new String(delivery.getBody());
System.out.println("Reciever .."+message);
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
channel.close();
connection.close();
return message;
答案 1 :(得分:0)
你没有
尝试过吗?channel.basicCancel(consumer.getConsumerTag());
线?
此外,做这样的事情要好得多:
while(true){
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message;
if (delivery != null) {
message = new String(delivery.getBody());
System.out.println("Reciever .."+message);
}
}
这样您只有一个消费者在循环中消费所有消息。这只是一个例子,我只是有办法彻底摆脱循环而不是必须ctrl-c。