Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Queue, multiple @RabbitListener but different services

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?

like image 697
Kenneth Gunnerud Avatar asked Jan 31 '23 00:01

Kenneth Gunnerud


1 Answers

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

like image 161
Artem Bilan Avatar answered Apr 09 '23 07:04

Artem Bilan