2017-05-21 15 views
0

創建連接下方,然後創建一個會話,然後從隊列中獲取一定量的消息。何時以及如何在異步消息監聽器的情況下關閉連接?

public class Consumer { 
    public static void main(String[] args) throws JMSException { 
     Consumer consumer = new Consumer(); // creates a connection and session 

     Destination destination = consumer.getSession().createQueue("JOBS"); 
     MessageConsumer messageConsumer = consumer.getSession().createConsumer(destination); 
     messageConsumer.setMessageListener(new Listener(job)); // asynchronous listener. 

     consumer.close(); // closes the connection 
    } 
} 

何時以及如何關閉連接?因爲當我這樣做時,只有一條消息被讀取! 如果我沒有像上面那樣關閉連接,所有的消息都會被讀取,所以沒問題,但連接保持打開狀態。

回答

0

由您來決定何時關閉連接。

您可以關閉前添加了Thread.sleep或添加shutdownHook關閉時卡紙停止:

Thread shutdownHook = new Thread(new Runnable() { 
     @Override 
     public void run() { 
      consumer.close(); 
     } 
    }); 

Runtime.getRuntime().addShutdownHook(shutdownHook); 

另一種方法:

的最大閒置時間(之前其套接字被認爲是 死亡),以毫秒爲單位。在某些平臺上, 套接字可能需要很長時間纔會死掉,因此如果 它們在一段時間內處於非活動狀態,我們允許代理終止連接。通過一些傳輸使用 啓用保持活躍心跳功能。設置爲值< = 0可禁用 不活動狀態監視。

當您創建與MQ代理的連接,那麼你應該創建一個這樣

cf = new ActiveMQConnectionFactory(
    "tcp://localhost:61616?wireFormat=openwire&wireFormat.maxInactivityDuration=value"); 

您可以指定使用wireFormat.maxInactivityDuration連接最大閒置時間,這個閱讀本ActiveMQ的文檔以瞭解更多詳情http://activemq.apache.org/cms/configuring.html

相關問題