我想在我的 JavaEE 6 项目中使用 JMS(主题)。我有一个类可以同时充当主题的发布者和订阅者。以下代码显示了该类中最重要的部分。
public class MessageHandler implements MessageListener {
private static TopicConnectionFactory factory;
private static Topic topic;
private TopicSubscriber subscriber;
private TopicPublisher publisher;
public MessageHandler() throws NamingException, JMSException {
if (factory == null) {
Context context = new InitialContext();
factory = (TopicConnectionFactory) new InitialContext()
.lookup("jms/myfactory");
topic = (Topic) context.lookup("jms/mytopic");
}
TopicConnection connection = factory.createTopicConnection();
connection.start();
TopicSession session = connection
.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
subscriber = session.createSubscriber(topic);
}
@Override
public void onMessage(Message message) {
try {
ObjectMessage msg = (ObjectMessage) message;
Object someO= msg.getObject();
System.out.println(this + " receives "+someO);
} catch (JMSException e) {
e.printStackTrace();
}
}
public void sendMessage(Object someO) {
try {
ObjectMessage msg = session.createObjectMessage();
msg.setObject(someO);
publisher = session.createPublisher(topic);
publisher.publish(msg);
publisher.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
我的问题是,如果这是设计这样一个类的好方法。我的想法是为订阅和发布共享一个连接和会话。但我担心这会导致一些开销或阻塞,因为我不会关闭连接、会话、订阅者和发布者,直到不再需要该对象。我在网上找到的所有示例都在发送或接收消息后直接关闭所有内容......
提前致谢!