问题描述
在使用JSF 2和Ajax的简单演示Web应用程序中,ManagedBean中有一个方法从JMS队列接收消息:
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;
}
}
每次getMessage都会打开/关闭JMS连接调用()方法。在bean生命周期中,我只需要打开和关闭JMS连接一次,以避免频繁的连接/断开操作?
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?
推荐答案
首先,将 Connection
移动为实例变量,以便可以从open,close和 getMessage $ c访问它$ c>方法。
First, move your Connection
to be a instance variable so that it can be accessed from your open, close, and getMessage
methods.
接下来,使用 PostConstruct
创建 openConnection
方法注释。
Next, create an openConnection
method with the PostConstruct
annotation.
@PostConstruct
public void openConnection() {
connection = connectionFactory.createConnection();
}
最后,创建 closeConnection
使用 PreDestroy
注释的方法。
Finally, create a closeConnection
method with the PreDestroy
annotation.
@PreDestroy
public void closeConnection() {
connection.close();
}
这篇关于我应该在JSF ManagedBean中打开/关闭JMS连接的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!