how to send response from consumer to producer to the particular request using Spring AMQP?

拥有回忆 提交于 2019-12-25 04:21:53

问题


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



来源:https://stackoverflow.com/questions/24772872/how-to-send-response-from-consumer-to-producer-to-the-particular-request-using-s

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