2011-06-07 114 views

回答

1

一個隊列是一個簡單的概念 - 多個源寫入隊列,單個消費者按照收到的順序逐個讀取消息。試圖引入隨機訪問混淆了這個概念,並與隊列中的意圖背道而馳。

如果您不能修改用戶刪除或消息進行排序,然後介紹中介隊列和消息驅動bean(MDB)做的工作:在MDB會消耗隊列Q消息,丟棄某些消息和在將消息發佈到隊列Q'之前重新排序其他消息。

前:

Q -> orignal consumer 

後:

Q -> your filtering and sorting MDB -> Q' -> original consumer 

這會保留在您的設計組件的意圖,是在我看來,更容易解釋和理解。

編輯:您的MDB可能看起來像下面顯示的示例(基於Java Enterprise Edition 6 tutorial)。本教程還包含有關打包和部署MDB的信息。

// MDB to consume messages on the original queue 
@MessageDriven(mappedName="jms/IncomingQueue", activationConfig = { 
     @ActivationConfigProperty(propertyName = "acknowledgeMode", 
            propertyValue = "Auto-acknowledge"), 
     @ActivationConfigProperty(propertyName = "destinationType", 
            propertyValue = "javax.jms.Queue") 
    }) 
public class MyMDB implements MessageListener { 
    @EJB 
    private MessageFilter messageFilter; 

    public void onMessage(Message message) { 
     // pass on to MessageFilter bean for processing 
     messageFilter.filter(message); 
    } 
} 

// singleton bean to filter and sort messages, then re-publish to the original consumer 
// if singleton doesn't work in your environment then you might have to persist the 
// messages using e.g. JPA 
@Singleton 
public class MessageFilter { 
    @Resource(name="jms/OutgoingQueue") 
    Queue outgoingQueue; 

    @Resource(name="jms/QueueConnectionFactory") 
    QueueConnectionFactory qcf; 

    // accept incoming message from the MDB 
    void filter(Message message) { 
     // filter and sort messages 
     ... 

     // send to queue read by the original consumer 
     send(message);    
    } 

    // send message to the filtered & sorted queue for the original consumer 
    void send(Message message) { 
     QueueConnection queueConnection = qcf.createQueueConnection(); 
     QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); 
     QueueSender queueSender = queueSession(outgoingQueue); 

     queueSender.send(message); 
    } 
} 

的Java EE 6教程也對how to create singleton beans例子,這裏有一個tutorial for connecting to a queue in order to send a message

+0

感謝您的回覆,您可以詳細介紹一下如何使用MDB實現這個功能嗎?我需要使用HornetQ Server API還是其他方法? – SmartSolution 2011-06-08 07:09:13

+0

@SmartSolution我已經添加了一個代碼示例。我希望這有幫助。 Java Enterprise Edition 6教程包含大量信息,這些信息解釋了我在上面的代碼中引入的註釋和概念。 – 2011-06-08 13:33:57

+0

謝謝金,可以請看看這個問題:http://stackoverflow.com/questions/6289050/how-to-get-details-of-messagereceivers-of-jms-queuehornetq-deployed-in-jboss-as6 – SmartSolution 2011-06-09 06:49:58