[英]JMS Standalone consumer with ActiveMQ and Spring
从历史上看,我已经将我的JMS使用者应用程序部署为在Tomcat(Windows框)下部署的Spring webapps。 然后,这些消费者将在同一个Tomcat实例下与我的其他Web应用程序一起运行。 然而,随着我使用的消费者数量的增长,我意识到这将成为一种维护噩梦。
我的解决方案是将这些webapps转换为部署为jar的“main method”独立应用程序。 实际上,我能够成功地将它们打包在一起,以尝试尽可能多地重用资源(DAO,依赖项等)。
这是我的主要方法:
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
try {
FooListener fooListener = (FooListener) context.getBean("fooListener");
fooListener.start();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
try {
BarListener barListener = (BarListener) context.getBean("barListener");
barListener.start();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
我的问题:
编辑:
更多信息:FooListener和BarListener扩展了以下抽象类。 它们从applicationContext.xml文件中的相应bean继承它们的值,并且它们都覆盖onMessage()方法以异步使用消息。
public abstract class TextMessageListener implements MessageListener {
protected ConnectionFactory connectionFactory;
protected String queueName;
protected String selectors;
public void start() throws JMSException {
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(session.createQueue(queueName), selectors);
consumer.setMessageListener(this);
connection.start();
}
public abstract void onMessage(Message message);
}
您必须以这种方式为应用程序上下文注册一个关闭钩子:
context.registerShutdownHook();
这将确保当jvm关闭时,上下文也会正常关闭。
我个人的偏好总是将它部署到容器 - 甚至是像这样的独立应用程序,这是由于以下原因:
另外,为什么要显式调用listener.start(),Spring容器会自动执行此操作?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.