首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法使用java在rabbitmq中分配来自传递回调块的消息

无法使用java在rabbitmq中分配来自传递回调块的消息
EN

Stack Overflow用户
提问于 2019-08-26 16:04:26
回答 1查看 648关注 0票数 1

我正在尝试使用Java来使用来自RabbitMQ的消息。我能够在传递回调块中获取和打印消息,但无法将值赋值给任何全局变量。

请看下面的问题,

代码语言:javascript
运行
复制
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必须是最终的或实际上是最终的。

EN

Stack Overflow用户

发布于 2019-08-26 18:01:21

使用包装器,因为不能更改lambda函数中的局部变量。任何包装都是好的。

在Java 8+中,可以使用AtomicReference:

代码语言:javascript
运行
复制
AtomicReference<String> value = new AtomicReference<>();
list.forEach(s -> {
  value.set("blah");
});

使用数组:

代码语言:javascript
运行
复制
String[] value = { null };
list.forEach(s-> {
  value[0] = "blah";
});

或者使用Java 10+:

代码语言:javascript
运行
复制
var wrapper = new Object(){ String value; }
list.forEach(s->{
  wrapper.value = "blah";
});
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57661344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档