在发送所有消息并在收到所有消息后释放时,我们怎样才能让生产者在春天amqp rabbitmq等待?

时间:2014-04-25 13:43:30

标签: java spring spring-batch spring-amqp

我将所有消息排队到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中的所有回复。我们怎么做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以使用任意数量的同步技术;例如,让侦听器putLinkedBlockingQueue中拥有回复,并让队列中的take(或poll超时)从队列中收到所有回复。

或者,根本不使用监听器,只需从回复队列中使用相同的RabbitTemplatereceive(),直到收到所有回复为止。

但是,如果队列为空,receive()将返回null,因此您必须在接收之间休眠以避免旋转CPU。