How do I verify that a JMS queue exists using Java

2019-04-06 13:45发布

How can I check whether a queue exists on a JMS server using the Java API? I don't want to send or receive any data to the queue for now, just verify that the queue exists. Also, the queue may be empty.

Here is my code sample. I have removed the error handling for simplicity.

    Connection connection = null;
    Session session = null;
    connection = factory.createConnection();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    //I was hoping this next line would throw an exception if the queue does not exist
    Queue queue = session.createQueue(queueName);

My JMS server is TIBCO EMS. I'm hoping for a solution that works on versions 5-7.

Solution

I followed the recommendation in the accepted answer but created a browser instead. The following line threw an exception as desired:

QueueBrowser browser = session.createBrowser(queue);

标签: java jms
2条回答
forever°为你锁心
2楼-- · 2019-04-06 14:19

Try creating a consumer or producer off the Session passing in the queue object you just created:

session.createConsumer(queue);

This should throw an InvalidDestinationException if the queue (or topic) does not exist.

查看更多
时光不老,我们不散
3楼-- · 2019-04-06 14:19

This is dependent on the provider, but you wont know in most cases until you create the session type, such as session.createConsumer. Simply creating a consumer this way will not consume any messages until you do a receive. And it is here the behavior may change from provider to provider and configuration of the server.

For example with ActiveMQ, assuming there are no permissions blocking the user you are connecting with, the queue is created automatically when you create the session type.

With WebSphere MQ, the queue has to be defined by an admin. If it does not exist, the queue manager will return an exception with a reason code of 2085 (UNKNOWN_OBJECT_NAME).

Outside of this, you'd need to see if the particular provider had a way to access a list of queues. Using the above examples, ActiveMQ you can get the list of queues using JMX, with WebSphere MQ, you can do this if you have permissions to send PCF commands to the queue manager.

查看更多
登录 后发表回答