如何return RabbitMQ数据到客户端(网站用户)

How to return RabbitMQ data to the client (website user)

我正在研究 RabbitMQ,我想知道如何 return 它处理的数据到客户端(网站用户)。

我正在考虑的流程包含一个 REST 端点,用户在该端点请求处理大约需要 5 秒才能完成的内容。所以用户请求它,web 服务将请求转发到 RabbitMQ 队列,该队列将在 docker 容器中最多有 10 个消费者侦听它并准备处理请求。到目前为止一切顺利,我可以做到这一点。问题是,消费者完成处理后,我如何 return 将数据发送给用户? 记住下面的设计,为了更好地理解,这里有一张图片:

所以换句话说,它会是这样的:

1 - 生产者(rest)接收请求并将消息发送到 RabbitMQ。

2 - RabbitMQ 将消息转发给任何监听的消费者。

3 - 消费者处理数据。

4 - 这就是我迷路的地方。我怎样才能return生成数据给客户端(网站用户)?还有一点,用户会一直等待请求结束,后面不需要再发送了。

为了更好的细节,我使用 java,其余部分是 spring 引导。

图片:

Request Reply Messaging

使用 RabbitTemplatesendAndReceive() 方法之一。

在消费者方面,只需 return 您的 @RabbitListener 方法的结果。

@RabbitListener(queues = "foo")
public String process(String in) {
    return in.toUpperCase();
}

编辑

@SpringBootApplication
public class So56025184Application {

    public static void main(String[] args) {
        SpringApplication.run(So56025184Application.class, args);
    }

    @Bean
    public ApplicationRunner runner(RabbitTemplate template) {
        return args -> {
            Scanner scanner = new Scanner(System.in);
            String toSend = scanner.nextLine();
            while (!"quit".equals(toSend)) {
                System.out.println(template.convertSendAndReceive("q1", toSend));
                toSend = scanner.nextLine();
            }
            scanner.close();
        };
    }

    @RabbitListener(queues = "q1")
    public String listen(String in) {
        return in.toUpperCase();
    }

    @Bean
    public Queue queue() { // RabbitAdmin will add this to the broker
        return new Queue("q1");
    }

}

您可以 send/receive 丰富的对象(而不是简单的字符串),使用 Java 序列化(和默认的 SimpleMessageConverter,或转换为 JSON,使用 Jackson2JsonMessageConverter.