Imagine a situation where developers need to communicate with queue managers using programs. IBM MQ extends API support for Java developers to work with MQ in their applications. Benefit of using API is MQ SERVER not necessarily installed on the developer’s machine to communicate with IBM MQ Queue managers.

In this article we will see how we can write messages to the local queue and browse them back using Java.

Connecting to a queue manager

In order to manipulate a message queue first we should connect to a local queue manager using MQQueueManager class.

  • This step is optional if you want to communicate with the default queue manager

Opening the queue

A queue can be opened for various purposes such as put, browse, inquire etc. We specify our purpose of opening the queue by specifying Open Options.

Queue open options

MQConstants.MQOO_OUTPUT

Opens the destination queue to put messages

MQConstants.MQOO_INPUT_EXCLUSIVE

Opens the queue to get messages with exclusive access. If the queue is already in use, the call will fail.

MQConstants.MQOO_INPUT_SHARED

Opens the queue if it is already opened by some other application for retrieving messages.

MQConstants.MQOO_INQUIRE

Used to inquire queue attributes such as queue depth

MQConstants.MQOO_INPUT_AS_Q_DEF

Opens queue with default queue attribute.

MQConstants.MQOO_BROWSE

Opens the queue to browse messages.

In order to communicate with any queue, we need to supply queue name and open options along with it to the queue manager.

Construct and write message into queue

Create an instance of MQMessage class, call writeString/wtriteUTF etc., supply your message as a string argument. That constructs a message.

To put message into queue we need to pass our message and put message options as parameters to put method of MQQueue instance.

Browse message from queue

To browse a message from queue, we need pass MQMessage object along with get message options object to the get method of MQQueue instance.

Closing the queue

Closing the queue after manipulating it is always a best practice. We should use close() method of MQQueue class to close a queue.

Code snippet to put message into queue

MQQueueManager qManager = new MQQueueManager ("queue manager name");
int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF | MQConstants.MQOO_OUTPUT | MQConstants.MQOO_BROWSE;
MQQueue queue = qMgr.accessQueue(“queue name", openOptions);
MQMessage msg = new MQMessage();
msg.writeString("Your message");
MQPutMessageOptions pmo = new MQPutMessageOptions();
queue.put(msg, pmo);

Code snippet to read message from queue

MQGetMessageOptions gmo = new MQGetMessageOptions();
queue.get(msg, gmo);
msgText = msg.readString();


keep up with the latest Element Blue updates by following us @Elementblue_IN.