【发布时间】:2015-10-16 07:11:39
【问题描述】:
我正在为系统集成主题开发一个小项目,并且我正在使用 JMS (JBOSS)。我们必须使用持久的主题,这部分很容易。问题是,假设我使用以下代码:
TopicConnectionFactory topicConnectionFactory = InitialContext.doLookup("jms/RemoteConnectionFactory");
try(JMSContext jmsContext = topicConnectionFactory.createContext(<username>,<password>)) {
Topic topic = InitialContext.doLookup(<topic>);
JMSConsumer jmsConsumer = jmsContext.createDurableConsumer(topic, <client-id>);
Message message = jmsConsumer.receive();
if(message != null) {
result = message.getBody(ArrayList.class);
}
}
这个 try-with-resources 很有用,因为它会在块结束时破坏连接。但是假设我在 JMSConsumer 等待消息时中断了程序。当我重新启动程序时,它会抛出:
javax.jms.IllegalStateRuntimeException: Cannot create a subscriber on the durable subscription since it already has subscriber(s)
有没有办法在程序中断时关闭连接/取消订阅/某些东西?
【问题讨论】:
-
你能捕捉到中断的异常,做一些清理,然后重新抛出它吗?
-
我尝试添加一个 ShutdownHook,但它不起作用。我会再次检查文档,我可能试图以错误的方式关闭连接,我不知道。