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

问题描述 投票:0回答:1

是否可以有一个@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 调用。 有人知道是否可以使用请求类型作为要使用的限定符?

rabbitmq amqp spring-amqp
1个回答
9
投票

这在方法级别上与

@RabbitListener
不起作用,但在类级别上使用方法上的
@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/amqp/receiving-messages/async-annotation-driven/method-selection.html

© www.soinside.com 2019 - 2024. All rights reserved.