【发布时间】:2019-12-30 20:21:02
【问题描述】:
我正在尝试使用 Java-Maven 使用来自 RabbitMQ 的消息。我能够在传递回调块中获取并打印消息,但无法将值分配给任何全局变量。
请看下面的问题,
public String newRmqConsumer(String queue) {
String QUEUE_NAME = queue;
String response = null;
System.out.println("****** Consumer service ******");
try {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("queueone");
factory.setPassword("queueone");
factory.setHost("localhost");
factory.setPort(4545);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
System.out.println("Queue Name: "+QUEUE_NAME);
System.out.println("1. Consuming Message...");
String getMsg;
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
getMsg = message;
System.out.println( "2. \"" + message + "\" message received");
};
response = channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return response;
}
错误:
在封闭范围内定义的局部变量 getMessage 必须是 final 或有效 final
【问题讨论】:
-
为什么要分配给传递回调之外的变量?此回调针对每条条消息执行。为每条消费的消息覆盖一个变量的用例是什么?
-
因为我想阅读消费的消息。请以其他方式告诉我。
-
您已经在
deliverCallback中以String message的形式阅读了邮件。您只需打印即可处理它。您应该扩展deliverCallback的主体,以便对所消费的消息做更多的事情,而不仅仅是打印它。根据消费的消息,你想做什么?
标签: java rabbitmq message-queue producer-consumer