簡體   English   中英

JMS隊列接收消息?

[英]JMS queue receive message?

在JMS API文檔中,它說:

 public Message receive() throws JMSException 

接收為此消息使用者生成的下一條消息。 此調用將無限期地阻塞,直到生成消息或此消息使用者關閉為止。

如果此接收在事務中完成,則使用者會保留該消息,直到事務提交為止。

這里我有三個問題:1。在代碼中,我們需要while循環來接收消息嗎? 喜歡:

while(true){
    Message msg = queue.receive();
    ....
}
  1. 什么是交易設置? 如何提交交易? 像這樣:

     boolean transacted = false; session = connection.createQueueSession(transacted, Session.AUTO_ACKNOWLEDGE); 
  2. receiveNoWait()有事務支持嗎? 如何使用它 ?

謝謝

  1. 如果您打算使用接收,那么您將需要某種循環來在收到第一個消息后繼續接收消息。 請記住,您還可以設置messagelistener並通過回調方法獲取接收的消息異步,而不必阻止。

  2. 默認情況下,事務通常設置為AUTO_ACKNOWLEDGE,這意味着一旦從隊列中獲取消息,它就會消失,無法回滾。 如果要設置事務,則需要將會話設置為事務處理,將方法設置為SESSION_TRANSACTED。 在會話上調用commit()時,將在隊列中確認消息。

  3. 如果正確設置確認模式並且在會話上使用commit()和rollback(),則receiveNoWait()可以具有事務支持。

如果我是你,我會創建一個MessageListener,而不必擔心旋轉線程來輪詢接收方法。 請記住,一旦創建會話,就會啟動隱式事務。

public class JmsAdapter implements MessageListener, ExceptionListener
{
    private ConnectionFactory connFactory = null;
    private Connection conn = null;
    private Session session = null;

    public void receiveMessages() 
    {
        try
        {
            this.session = this.conn.createSession(true, Session.SESSION_TRANSACTED);

            this.conn.setExceptionListener(this);

            Destination destination = this.session.createQueue("SOME_QUEUE_NAME");

            this.consumer = this.session.createConsumer(destination);

            this.consumer.setMessageListener(this);

            this.conn.start();
        } 
        catch (JMSException e) 
        {
            //Handle JMS Exceptions Here
        }
    }

    @Override
    public void onMessage(Message message) 
    {
        try
        {
            //Do Message Processing Here

            //Message sucessfully processed...  Go ahead and commit the transaction.
            this.session.commit();
        }
        catch(SomeApplicationException e)
        {
            //Message processing failed.
            //Do whatever you need to do here for the exception.

            //NOTE: You may need to check the redelivery count of this message first
            //and just commit it after it fails a predefined number of times (Make sure you
            //store it somewhere if you don't want to lose it).  This way you're process isn't
            //handling the same failed message over and over again.
            this.session.rollback()
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM