我将所有消息排队到rabbitmq队列并处理远程服务器上的消息。下面是我在同一类中的生产者和回复处理程序。
public class AmqpAsynchRpcItemWriter<T> implements ItemWriter<T>,
MessageListener {
protected String exchange;
protected String routingKey;
protected String queue;
protected String replyQueue;
protected RabbitTemplate template;
// Reply handler
@Override
public void onMessage(Message message) {
try {
String corrId = new String(message.getMessageProperties()
.getCorrelationId(), "UTF-8");
System.out.println("received " + corrId + " from " + this.replyQueue);
} catch (IOException e) {
e.printStackTrace();
}
}
//Producer
@Override
public void write(List<? extends T> items) throws Exception {
for (T item : items) {
System.out.println(item);
System.out.println("Queing " + item + " to " + this.queue);
Message message = MessageBuilder
.withBody(item.toString().getBytes())
.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
.setReplyTo(this.replyQueue)
.setCorrelationId(item.toString().getBytes()).build();
template.send(this.exchange, this.routingKey, message);
System.out.println("Queued " + item + " to " + this.queue);
}
// It should wait here untill we get all replies in onMessage, How can we do this ?
}
我将使用write方法发送所有消息并在onMessage中获取回复。这是正常工作,但写不等待回复,它返回到调用者和弹簧批步骤标记完成。
但是我希望进程在发送所有消息之后等待回复,直到我们收到onMessage中的所有回复。我们怎么做到这一点?
答案 0 :(得分:0)
您可以使用任意数量的同步技术;例如,让侦听器put
在LinkedBlockingQueue
中拥有回复,并让队列中的take
(或poll
超时)从队列中收到所有回复。
或者,根本不使用监听器,只需从回复队列中使用相同的RabbitTemplate
到receive()
,直到收到所有回复为止。
但是,如果队列为空,receive()
将返回null
,因此您必须在接收之间休眠以避免旋转CPU。