我正在尝试使用Java来使用来自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必须是最终的或实际上是最终的。
发布于 2019-08-26 18:01:21
使用包装器,因为不能更改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";
});https://stackoverflow.com/questions/57661344
复制相似问题