我正在尝试使用 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 必须是最终的或有效的最终
使用包装器,因为您无法更改 lambda 函数内部的局部变量。 任何类型的包装纸都可以。
对于 Java 8+,请使用 AtomicReference:
AtomicReference<String> value = new AtomicReference<>();
list.forEach(s -> {
value.set("blah");
});
使用数组:
String[] value = { null };
list.forEach(s-> {
value[0] = "blah";
});
或者使用 Java 10+:
var wrapper = new Object(){ String value; }
list.forEach(s->{
wrapper.value = "blah";
});
Declare the array list and add the message to it.
List<String> msglist=new ArrayList<>();
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
msglist.add(message);
System.out.println( "2. \"" + message + "\" message received");
};