How I can implement an asynchronous JMS application? Is it necessary to change server program or just I should change the client code? I want to know How I can change a synchronous JMS messaging to asynchronous?
2
votes
2 Answers
2
votes
1
votes
Message Driven Beans in Java EE are async. by nature. A simple MDB could look like this:
@MessageDriven(mappedName = "jms/MyQueue") // JNDI name for a specific Destination (queue or topic)
public class MyMDB implements MessageListener{
public void onMessage(Message msg){
// handle it async.
}
}
Otherwise, in plain java/JMS, it's almost as simple, same code, but instead of the @MessageDriven annotation, some init code has to be done to get the JMS consumer up and running. Also standard JMS setup procedure has to be done, of course, like getting a connection factory, creating a connection and lookup a destination.
public class MyConsumer implements MessageListener{
public void init(Connection conn, Destination dest){
// connection and destination from JNDI, or some other method.
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer cons = sess.createConsumer(dest);
cons.setMessageListener(this);
conn.start();
}
@Override
public void onMessage(Message msg) {
// Do whatever with message
}
}