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

百般思念 提交于 2020-01-01 12:01:09

问题


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?


回答1:


First, move your Connection to be a instance variable so that it can be accessed from your open, close, and getMessage methods.

Next, create an openConnection method with the PostConstruct annotation.

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

Finally, create a closeConnection method with the PreDestroy annotation.

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



回答2:


How about in the servlet context listener?

Just define in web.xml

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

And then implement a servletContextListener

public final class contextListenerClassimplements ServletContextListener {
...
}

Other solution can be to use SessionListener...



来源:https://stackoverflow.com/questions/5870342/where-should-i-open-close-jms-connections-in-a-jsf-managedbean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!