2
votes

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
JMS is asynchronous by nature, I don't understand you, are you programer? - Ramanqul Buzaubak
No, I just searched about asynchronous approaches in j2ee,when I'm being familiar by jms, I see that clients can receive messages from servers asynchronously. I want to know how I can do it? - Azad

2 Answers

2
votes

Very simple. You need to assign a message listener to your consumer to receive messages asynchronously.

consumer.setMessageListener(new MessageListener).

Googling will get you a number of samples.

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

   }
}