Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

purge rabbitmq queue using spring amqp template?

I am adding messages to rabbitmq queue using spring amqp template in my spring batch item writer.

public class AmqpAsynchRpcItemWriter<T> implements ItemWriter<T> {

    protected String exchange;
    protected String routingKey;
    protected String queue;
    protected String replyQueue;
    protected RabbitTemplate template;
    BlockingQueue<Object> blockingQueue;


    public void onMessage(Object msgContent) {

        try {
            blockingQueue.put(msgContent);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void write(List<? extends T> items) throws Exception {

        for (T item : items) {

            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);

        }

        for (T item : items) {

            Object msg = blockingQueue.poll(60, TimeUnit.SECONDS);

            if (msg instanceof Exception) {
                throw (Exception) msg;
            } else if (msg == null) {
                System.out.println("reply timeout...");
                break;
            } 

        }
    }

}

Messages are going to be processed on different remote servers. I am trying to handle the use case where if my message processing is failed (due to some exception) the step execution will be stopped.

I want to purge all the remaining messages in that queue so that remaining messages in queue should not be consumed and processed as they will also be failed.

If the step is failed, my item writer will again queue all the messages, so I need to purge all remaining message on any exception.

How can I purge the queue using spring amqp ?

like image 484
vishal Avatar asked Oct 29 '25 03:10

vishal


1 Answers

I could do it using

admin.purgeQueue(this.queue, true);

like image 154
vishal Avatar answered Oct 31 '25 15:10

vishal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!