javaqueueactivemq-artemispurge

How to purge a queue in ActiveMQ Artemis programmatically using Java?


I am new to using ActiveMQ Artemis, and I am trying to purge one queue programmatically. I have searched through the documentation, and online but have not been able to find anything to help with this.

I would like an example of how to do this given a name if a queue using Java.

ClientSessionFactory sessionFactory;
ClientSession session
ClientProducer producer

//Creating the queue as follows:
session = sessionFactory.createSession();
producer = session.createProducer(queueName);
session.start();

Solution

  • Most messaging APIs and protocols do not provide a way to purge (i.e. clear all messages from) a queue. The two basic operations you normally get are producing and consuming. Such is the case with the "core" API provided by ActiveMQ Artemis.

    That said, there is a management API which provides a way to purge a queue because this is something typically reserved for administrators who may be managing the broker. The management API is based on JMX MBeans so it can be accessed via JMX and a handful of other methods (e.g. web console, HTTP via Jolokia, management "messages").

    For Java applications the jmx example which ships with ActiveMQ Artemis in the examples/features/standard/jmx directory demonstrates exactly what you want to do. It uses the removeMessages method of the QueueControl with a null filter value to remove all the messages from the queue. Here's a quick summary:

    import javax.management.MBeanServerConnection;
    import javax.management.MBeanServerInvocationHandler;
    import javax.management.ObjectName;
    import javax.management.remote.JMXConnector;
    import javax.management.remote.JMXConnectorFactory;
    import javax.management.remote.JMXServiceURL;
    
    import org.apache.activemq.artemis.api.core.RoutingType;
    import org.apache.activemq.artemis.api.core.SimpleString;
    import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder;
    import org.apache.activemq.artemis.api.core.management.QueueControl;
    
    ...
    
    ObjectName on = ObjectNameBuilder.DEFAULT.getQueueObjectName(SimpleString.toSimpleString(queueName), SimpleString.toSimpleString(queueName), RoutingType.ANYCAST);
    JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi"));
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();
    QueueControl queueControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, on, QueueControl.class, false);
    queueControl.removeMessages(null);
    

    For more details on running the examples see the "Examples" chapter in the documentation.

    For more details on the management API and broker management in general (including configuration changes necessary to enable remote JMX access) see the "Management" chapter in the documentation.