2015-10-15 124 views
1

我正在开发一个系统集成主题的小型项目,并且正在使用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) 

有没有办法关闭连接/取消/某物的程序被中断时?

+1

你能抓住interruptedexception,做一些清理,然后重新抛出吗? –

+0

我试着添加一个ShutdownHook,但它不起作用。我会再次检查文档,我可能会试图以错误的方式关闭连接,我不知道。 – Budgerous

回答

0

基本上,我用下面的代码:

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>); 
    Runtime.getRuntime().addShutdownHook(new Thread() { 
     public void run() { 
      jmsConsumer.close(); 
      this.interrupt(); 
     } 
    }); 
    Message message = jmsConsumer.receive(); 
    if(message != null) { 
     result = message.getBody(ArrayList.class); 
    } 
} 

我想用jmsContext.stop()来关闭连接。无论如何,它不工作,现在是。耶,我。

1

如果你需要做一些清理工作,但无法下咽的异常,可以捕获该异常,做一些清理,然后重新抛出原始异常:

try(JMSContext jmsContext = topicConnectionFactory.createContext(<username>,<password>)) { 
    // ... 
} catch (InterruptedException e) { 
    // Do some cleanup. 
    throw e; 
} 

(我假设它是一个InterruptedException,因为你说:“说我中断程序” - 但也许这是一些其他类型的:同样的想法适用)

+0

其实我的意思是像键盘中断,或通过IDE停止进程。我真的不知道是否会抛出一个InterruptedException ... – Budgerous

+1

为什么不尝试 - 暂时 - 如果你“中断”了进程,看看抛出了什么呢? (只是不要把它作为'catch Exception'长期使用) –

+0

谢谢,事实证明我只是以错误的方式关闭连接。我会发布答案。 – Budgerous