我应该在 JSF ManagedBean 中的哪里打开/关闭 JMS 连接?
在使用 JSF 2 和 Ajax 的简单演示 Web 应用程序中,ManagedBean 中有一个从 JMS 队列接收消息的方法:
@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 连接,以避免频繁的连接/断开操作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,将
Connection
移动为实例变量,以便可以通过 open、close 和getMessage
方法访问它。接下来,使用
PostConstruct
注释创建一个openConnection
方法。最后,使用
PreDestroy
注释创建一个closeConnection
方法。First, move your
Connection
to be a instance variable so that it can be accessed from your open, close, andgetMessage
methods.Next, create an
openConnection
method with thePostConstruct
annotation.Finally, create a
closeConnection
method with thePreDestroy
annotation.在 servlet 上下文监听器中怎么样?
只需在 web.xml 中定义
,然后实现一个 servletContextListener
其他解决方案可以是使用 SessionListener...
How about in the servlet context listener?
Just define in web.xml
And then implement a servletContextListener
Other solution can be to use SessionListener...