使用多个MessageListener线程重复JMS消息处理

时间:2012-04-17 12:22:58

标签: multithreading jms duplicates message

我正在创建一个侦听队列的JMS侦听器应用程序。我正在使用TIBCO JMS 实现并面临一个间歇性地超过我的一个监听器线程的问题 选择相同的消息并导致重复处理。

以下是我创建连接的方式:     。     ..     ...

Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.PROVIDER_URL, url);
env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClass);
env.put(Context.SECURITY_PRINCIPAL, userName);

String decryptedPass = null;
//Decryption logic

try {
    // Look up queue connection factory from naming context.
    if (log.isEnabledFor(Level.DEBUG)) {
        log.debug("Attempting to lookup queue connection factory at '" + 
                    this.url + "' as user '" + userName + "'.");
    }

    Context ctx = new InitialContext(env);

    QueueConnectionFactory factory = 
        (QueueConnectionFactory) ctx.lookup(connectionFactoryName);

    // Create JMS connection using the factory we just looked up.
    if (log.isEnabledFor(Level.DEBUG)) {
        log.debug("Creating queue connection as user '" + userName + "'.");
    }
    connection = factory.createQueueConnection(userName, decryptedPass);
    ...
    ..
    .

然后我在这里创建具有上面创建的相同连接的侦听器线程

        //This is called in a loop.
                    // Create a JMS session that is non-transacted, but in client
        // acknowledge mode.  This will allow us to control when
        // messages are acknowledged.
        QueueSession session = 
            getQueueConnection().createQueueSession(
                false, Tibjms.EXPLICIT_CLIENT_ACKNOWLEDGE);

        // Create a receiver for the queue we are interested in.  Then
        // set the message listener defined on the outer class.  Messages
        // will be delivered on a dispatcher thread created by the
        // JMS provider.
        Queue queue = session.createQueue(getQueueName());
        session.createReceiver(queue).setMessageListener(getListener());
        ...
        ..
        .

现在让我们假设,创建了5个侦听器线程,它们作为队列中的接收器进行侦听。我看到了一种行为 有时多个侦听器线程/接收器会收到相同的消息,我最终会重复处理?我怎么能够 通过JMS配置处理它?它甚至可能吗?或者我不得不求助于一些程序化的解决方案?任何建议 非常感谢。谢谢。

2 个答案:

答案 0 :(得分:2)

当消息传递到应用程序时,该消息将从队列中隐藏(或不可供其他使用者使用),直到应用程序确认它为止。只有在应用程序确认该消息后,才会从队列中删除该消息。如果消费者在没有确认的情况下离开,该消息将重新出现在队列中。因此,当隐藏消息时,该消息将不可用于其他消费者。

我想在这里提出的观点是:不应该同时向多个消费者发送消息。您可能需要重新检查您的侦听器代码。

答案 1 :(得分:0)

尝试将Tibjms.EXPLICIT_CLIENT_ACKNOWLEDGE更改为javax.jms.Session.AUTO_ACKNOWLEDGE

或确保Listener确认收到消息。