【发布时间】:2019-04-29 20:45:58
【问题描述】:
我们有一个 JMS 客户端需要处于空闲状态,直到它收到一条消息。当它收到一条消息时,它会执行一些功能,然后回到空闲状态。我的问题是,确保客户端保持正常运行的最佳方法是什么?让 JMS 客户端软件处理这个问题是一种好习惯,还是我们需要在主机上将软件作为服务运行(和/或做其他事情)?我们目前依赖 JMS 客户端软件,因为它似乎通过打开的连接保持线程处于活动状态,但我不确定这是否是最佳实践。我们使用 ActiveMQ 作为我们的消息代理和客户端软件。
编辑:添加代码示例
以下是客户端如何使用 JMS 客户端连接保持在线状态的示例:
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
public class JmsTestWithoutClose implements MessageListener {
private final Connection connection;
private final Session session;
private final MessageConsumer consumer;
public static void main(String[] args) throws JMSException {
System.out.println("Starting...");
JmsTestWithoutClose test = new JmsTestWithoutClose("<username>", "<password>", "tcp://<host>:<port>");
// if you uncomment the line below, the program will terminate
// if you keep it commented, the program will NOT terminate
// test.close();
System.out.println("Last line of main method...");
}
public JmsTestWithoutClose(String username, String password, String url) throws JMSException {
// create connection and session
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(username, password, url);
this.connection = factory.createConnection();
connection.start();
this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createTopic("Topic_Name");
consumer = session.createConsumer(destination);
consumer.setMessageListener(this);
}
public void close() throws JMSException {
session.close();
connection.close();
}
@Override
public void onMessage(Message message) {
// process the message
}
}
【问题讨论】: