In a simple demo web app using JSF 2 and Ajax, there is a method in the ManagedBean which receives messages from a JMS queue:
@ManagedBean
public class Bean {
@Resource(mappedName = "jms/HabariConnectionFactory")
private ConnectionFactory connectionFactory;
@Resource(mappedName = "jms/TOOL.DEFAULT")
private Queue queue;
public String getMessage() {
String result = "no message";
try {
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
Message message = consumer.receiveNoWait();
if (message != null) {
result = ((TextMessage) message).getText();
}
connection.close();
} catch (JMSException ex) {
Logger.getLogger(Bean.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
}
The JMS connection is opened / closed every time the getMessage() method is invoked. Which options do I have to open and close the JMS connection only once in the bean life cycle, to avoid frequent connect/disconnect operations?