Single Queue, multiple @RabbitListener but different services

前提是你 提交于 2019-12-04 04:16:47

问题


Is it possible to have a single @RabbitListener, e.g:

@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();
}

And on the consumer side, it will send requests to the same request queue, but with different operations? Now it converts the objects from Json to a object (e.g.: FindApplicationByIdRequest, or PingRequest).

But now, when i get it back:

@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);
}

It looks like it failed to correlate the two. So I call the ping method, then I get a FindApplicationByIdResponse back in that method. Why is that?

When I used different queues for them, it works fine. But I end up having to make a lot of queues to support all the RPC calls I wish to make. Anyone know if its possible to use the request type as a qualifier to which one it's going to use?


回答1:


That doesn't work with @RabbitListener on the method level, but it is possible on the class level with the @RabbitHandler on methods:

@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



来源:https://stackoverflow.com/questions/45066315/single-queue-multiple-rabbitlistener-but-different-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!