Java Messages Synchronous and Asynchronous
//The Consumer Class Consumes Messages in a Synchronous Manner public class Consumer { public static void main(String[] args) { try { // Gets the JNDI context Context jndiContext = new InitialContext(); // Looks up the administered objects ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/javaee7/ConnectionFactory"); Destination queue = (Destination) jndiContext.lookup("jms/javaee7/Queue"); // Loops to receive the messages try (JMSContext context = connectionFactory.createContext()) { while (true) { String message = context.createConsumer(queue).receiveBody(String.class); } } } catch (NamingException e) { e.printStackTrace(); } } }
//The Consumer Is a Message Listener public class Listener implements MessageListener { public static void main(String[] args) { try { // Gets the JNDI context Context jndiContext = new InitialContext(); // Looks up the administered objects ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/javaee7/ConnectionFactory"); Destination queue = (Destination) jndiContext.lookup("jms/javaee7/Queue"); try (JMSContext context = connectionFactory.createContext()) { context.createConsumer(queue).setMessageListener(new Listener()); } } catch (NamingException e) { e.printStackTrace(); } } public void onMessage(Message message) { System.out.println("Async Message received: " + message.getBody(String.class)); } }