Where should I open / close JMS connections in JSF ManagedBean?

In a simple demo web application using JSF 2 and Ajax, ManagedBean has a method that receives messages from the 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 opens / closes every time the getMessage () method is called. What parameters do I need to open and close the JMS connection only once in the bean life cycle to avoid frequent connect / disconnect operations?

+4
source share
2 answers

First, move Connection as an instance variable so that it can be retrieved from the open, close, and getMessage methods.

Then create an openConnection method with PostConstruct annotation.

 @PostConstruct public void openConnection() { connection = connectionFactory.createConnection(); } 

Finally, create a closeConnection method with a PreDestroy annotation.

 @PreDestroy public void closeConnection() { connection.close(); } 
+2
source

What about a servlet context listener?

Just define in web.xml

 <listener> <listener-class>contextListenerClass</listener-class> </listener> 

And then we implement servletContextListener

 public final class contextListenerClassimplements ServletContextListener { ... } 

Another solution might be to use SessionListener ...

0
source

All Articles