单个队列,多个@RabbitListener 但不同的服务

Single Queue, multiple @RabbitListener but different services

是否可以有一个@RabbitListener,例如:

@RabbitListener(queues = STORAGE_REQUEST_QUEUE_NAME)
public FindApplicationByIdResponse findApplicationById(FindApplicationByIdRequest request) {
    return repository.findByUuid(request.getId())
            .map(e -> new FindApplicationByIdResponse(conversionService.convert(e, Application.class)))
            .orElse(new FindApplicationByIdResponse(null));
}

@RabbitListener(queues = STORAGE_REQUEST_QUEUE_NAME)
public PingResponse ping(PingRequest request) {
    return new PingResponse();
}

而在消费者端,它会向同一个请求队列发送请求,但是有不同的操作?现在它将对象从 Json 转换为对象(例如:FindApplicationByIdRequest 或 PingRequest)。

但是现在,当我取回它时:

@Override
public FindApplicationByIdResponse findApplicationById(FindApplicationByIdRequest request) {
    Object object = template.convertSendAndReceive(Queues.STORAGE_REQUEST_QUEUE_NAME, request);
    return handleResponse(FindApplicationByIdResponse.class, object);
}

@Override
public PingResponse ping(PingRequest request) {
    Object object = template.convertSendAndReceive(Queues.STORAGE_REQUEST_QUEUE_NAME, request);
    return handleResponse(PingResponse.class, object);
}

它似乎未能将两者关联起来。因此,我调用了 ping 方法,然后在该方法中返回了一个 FindApplicationByIdResponse。 这是为什么?

当我为它们使用不同的队列时,它工作正常。但我最终不得不建立大量队列来支持我希望进行的所有 RPC 调用。 有人知道是否可以将请求类型用作将要使用的限定符吗?

这不适用于方法级别的 @RabbitListener,但可以在 class 级别使用 @RabbitHandler 方法:

@RabbitListener(queues = STORAGE_REQUEST_QUEUE_NAME)
public class MultiListenerBean {

    @RabbitHandler
    public String bar(Bar bar) {
        ...
    }

    @RabbitHandler
    public String baz(Baz baz) {
        ...
    }

    @RabbitHandler
    public String qux(@Header("amqp_receivedRoutingKey") String rk, @Payload Qux qux) {
        ...
    }

}

https://docs.spring.io/spring-amqp/reference/html/#annotation-method-selection