Sending messages to a JMS queue

I used openjms to develop this example. Download it, start up the server (startup.sh/bat) and create a queue testqueue (admin.sh/bat).

The following example sends a TextMessage to the testqueue queue in PERSISTENT delivery mode, meaning that the JMS server will store the message on secondary storage to prevent loosing the message with server failures or crashes. The message stays there until delivered to all the consumers.

Main.java:

import javax.naming.*;
import java.util.*;
 
import javax.jms.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      // Load Context for OpenJMS
      Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY,"org.exolab.jms.jndi.rmi.RmiJndiInitialContextFactory");
      env.put(Context.PROVIDER_URL, "rmi://localhost:1099/JndiServer");
      Context ctx = new InitialContext(env);
  
      QueueConnectionFactory cnxFactory = (QueueConnectionFactory) ctx.lookup("JmsQueueConnectionFactory");
 
      Connection connection = ((QueueConnectionFactory) cnxFactory).createQueueConnection();
      QueueSession session = ((QueueConnection) connection).createQueueSession(
                                   false, Session.CLIENT_ACKNOWLEDGE);
      Queue queue = session.createQueue("testqueue");
      QueueSender sender = session.createSender(queue);
      sender.setDeliveryMode(javax.jms.DeliveryMode.PERSISTENT);
 
      TextMessage textMsg = session.createTextMessage();
      textMsg.setText("Hello world!");
      sender.send(textMsg);
      System.out.println("Message sent!");
  
      System.exit(1);
   }
}