how to send response from consumer to producer to

2019-08-19 11:32发布

问题:

we have one problem statement in our application where we are getting null response at the producer end.

1> Producer will produce message (REQUEST_QUEUE) and it will wait for the response.

Object receivedData = amqpTemplate.convertSendAndReceive("IKEY123456");
System.out.println("RESPONSE DATA: " + receivedData);

2> At consumer end it will consume message and

Class TestConsumer {
    AmqpTemplate amqpTemplate;

    public void methodA(){
        String msg = (String)amqpTemplate.receiveAndConvert()
        process(msg);
    }

    public void process(String msg){
        // ... process something on that message
        Object resData = service.makeChanges(msg);

        // I want to send 'resData" object back to the producer
        amqpTemplate.convertAndSend(resData);
    }
}

Response at producer end is null. "RESPONSE DATA: null"

Can anyone tell me how to send response back to producer and how to achieve correct response received to the request which we send.

回答1:

The main trick in request/reply patter in the messaging is correlation.

By default the RabbitTemplate creates a new temporary queue for each reply and populate it to the replyTo message property.

You main issue on the consumer side that you don't send a reply to that replyTo queue from the request.

Would be better and straightforward, if you will use the SimpleMessageListenerContainer to receive a request from the requestQueue. In this case you can use your TestConsumer as POJO listener and wrap it to the MessageListenerAdapter. The last one takes care about replyTo and correlationId:

@Bean
public SimpleMessageListenerContainer serviceListenerContainer() {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(rabbitConnectionFactory());
    container.setQueues(requestQueue());
    container.setMessageListener(new MessageListenerAdapter(new PojoListener()));
    return container;
}

public class PojoListener {

    public String handleMessage(String foo) {
        return foo.toUpperCase();
    }
}

It is the simplest way to correlate.

Another case is around the fixed replyQueue, replyListener and, of course, the correlationId for the request and reply. There is need more configurations on producer side, but the consumer part is the same - SimpleMessageListenerContainer with MessageListenerAdapter.

You can get more info from the Reference Manual



标签: spring-amqp