by
0 16

Reading Messages from a Queue with a MessageConsumer in JMS

The code shows how to read messages from a queue using a Message Consumer in java Java Message Service.
MessageConsumer object is created from the Session object, defined as non-transacted and auto-acknowledged, invoking createConsumer method. Such method will bind the consumer to the queue defined via JNDI lookup table.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/42221/Reading-Messages-from-a-Queue-with-a-Mes?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
//Creating a non-transacted, auto-acknowledged session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //Creating messageConsumer bound to destination queue MessageConsumer messageConsumer = session.createConsumer(destination); connection.start(); Message message; boolean end = false; //read while (!end) { message = messageConsumer.receive(); String text; if (message instanceof TextMessage) { text = ((TextMessage) message).getText(); } else { byte[] body = new byte[(int) ((BytesMessage) message).getBodyLength()]; ((BytesMessage) message).readBytes(body); text = new String(body); } if (text.equals("EXIT")) { System.out.println("Received exit message " + text); end = true; } else { System.out.println("Received message: " + text); } } //Tear down connection connection.close();

Other Steps and Solutions

If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus