by
0 16

How to send messages using MessageProducer in JMS

The code shows how to send messages using a MessageProducer in Java Message Service.
Destination object is the queue where to send, read as JNDI lookup queue.
The Session used is not transactional and auto acknowledged.
Note the delivery mode of send method is set to Persistent, so the message will be persisted by JMS broker and its delivery will be guaranteed.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/42225/How-to-send-messages-using-MessageProduc?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
// Load JNDI properties Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream("my.properties")); //Create the initial context Context ctx = new InitialContext(properties); // look up destination and connection factory Destination destination = (Destination)ctx.lookup("myQueue"); ConnectionFactory conFac = (ConnectionFactory)ctx.lookup("Connectionfactory"); Connection connection = conFac.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(destination); TextMessage message; // Send a series of messages in a loop for (int i = 1; i < 100; i++) { message = session.createTextMessage("Message " + i); messageProducer.send(message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus