【问题标题】:Unable to assign message from delivery callback block in rabbitmq with java无法使用java从rabbitmq中的传递回调块分配消息
【发布时间】: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


【解决方案1】:

使用包装器,因为您无法更改 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";
});

【讨论】:

    猜你喜欢
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 2014-02-17
    • 2015-10-02
    • 2014-11-27
    相关资源
    最近更新 更多