Java 如何在 IBM MQ 中实现逻辑排序?

How to implement Logical ordering in IBM MQ in Java?

我们有一个用例,可以放置一组具有相同 groupId 但 MessageSequenceNumber 不同的消息。这用于对消息进行逻辑排序,以便在接收方,接收方可以根据组顺序对所有消息进行分组。我正在关注 IBM MQ v7.5 知识中心页面“Message groups”。

我编写了一个代码来放置消息:-

public boolean writeMessage(String[] messages, String queueName) {          

                Session session = getQueueConnection().createSession(true,
                    Session.AUTO_ACKNOWLEDGE);


            Destination destination = session.createQueue(queueName);
            messageProducer = session.createProducer(destination);
            for (int i = 0; i < messages.length; i++) {
                TextMessage message = session.createTextMessage(messages[i]);
                messageProducer.send(message);
            }

            // Commit the send (Actually put messages to Queue)
            session.commit();
            return true;
}

现在,我想为数组中的所有消息添加一个唯一的 groupID,并添加一个序列号 (msgSeqNum) (1,2,3..)。我怎样才能通过 JMS API 做到这一点?我正在 IBM IIB v8 知识中心页面“Sending messages in a WebSphere MQ message group.

上查找代码的 JMS 版本

David Currie 在 2006 年写了一篇很好的 IBM developerWorks 博客,标题为“使用 WebSphere MQ Java 和 JMS API 对消息进行分组”,其中描述了如何按照您的要求进行操作,但看起来这是最近被 IBM 删除。


Wayback Machine link to "Grouping messages using the WebSphere MQ Java and JMS APIs"


下面是 David 在 post 中提供的信息,看来与获取逻辑相比,放置逻辑更容易实现。我只在此处包含放置逻辑代码,因为这是您询问的内容。我通过电子邮件联系了大卫,询问是否会重新发布此博客。

Sending a message group

Let's start by looking at the sending application. As mentioned above, the put message option MQPMO_LOGICAL_ORDER was simply an instruction to the queue manager to automatically allocate message group identifiers and sequence numbers. The example in Listing 3 below demonstrates how, in the absence of this option in the JMS API, we can set these properties explicitly.

Listing 3. Sending a message group using the WebSphere MQ JMS API

MQConnectionFactory factory = new MQConnectionFactory();
factory.setQueueManager("QM_host")
MQQueue destination = new MQQueue("default");
destination.setTargetClient(JMSC.MQJMS_CLIENT_NONJMS_MQ);
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(destination);
 
String groupId = "ID:" + new BigInteger(24 * 8, new Random()).toString(16);
 
for (int i = 1; i <= 5; i++) {
 
    TextMessage message = session.createTextMessage();
    message.setStringProperty("JMSXGroupID", groupId);
    message.setIntProperty("JMSXGroupSeq", i);
 
    if (i == 5) {
        message.setBooleanProperty("JMS_IBM_Last_Msg_In_Group", true);
    }
 
    message.setText("Message " + i);
    producer.send(message);
 
}
 
connection.close();