Reputation: 253
I know the small part that setMessageListener is used when we implements MessageListener on the class. This below class is for reciever. Both subscribe and publish method are in same class. When i try to execute this my application won't recieve message. It is not producing message also probably because of some error in subscribe method , i am not sure.
public void subscribe(Connection topicConnection, Topic topic) throws JMSException{
TopicSession subscribeSession= (TopicSession) topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
topic=subscribeSession.createTopic("topic/mohit");
TopicSubscriber topicSubscriber=subscribeSession.createSubscriber(topic);
topicConnection.start();
Message message=topicSubscriber.receive();
TextMessage textmessage=(TextMessage) message;
System.out.println(textmessage.getText());
}
}
But when i have below code with class extending from MessageListener interface and instead of Message message=topicSubscriber.receive(); i use topicSubscriber.setMessageListener(new Chat()); the application runs fine.Please tell me what is wrong in first implementation.
public void subscribe(Connection topicConnection, Topic topic) throws JMSException{
TopicSession subscribeSession= (TopicSession) topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
topic=subscribeSession.createTopic("topic/mohit");
TopicSubscriber topicSubscriber=subscribeSession.createSubscriber(topic);
topicSubscriber.setMessageListener(new Chat());
}
@Override
public void onMessage(Message message) {
try {
System.out.println(((TextMessage) message).getText());
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: 0
Views: 6638
Reputation: 15273
Both receive()
method and a MessageListener
are both used for receiving messages.
1) The receive()
method is a blocking call meaning the method will not return until a message is received or connection is closed.
2) The MessageListener
is the callback
way of receiving messages. Application attaches the MessageListener to a consumer/subscriber object instance. The JMS implementation calls back the onMessage
method of MessageListener
whenever there is a message to be delivered to application. In simple terms the MessageListener.onMessage
method is invoked from a different thread and hence it does not block the application thread like the receive
method.
Possible reasons on why the receive() method is not getting any publications
1) There were no publications to receive. Hence receive method is waiting.
2) You have not shown the whole code, So I making a guess: You are receiving and publishing from the same thread. Since receive call is blocked, publish code which is after receive()
is never executed.
Upvotes: 4