java - 以多线程方式浏览Jms Queue

标签 java jms spring-batch

我有一个浏览队列消息的 spring-batch,这个队列应该包含大量消息。然后需要很多时间来治疗所有的人。因此我想到了多线程来处理这个问题,但我还不清楚。

以下是在没有多线程的情况下浏览队列的示例:


import java.net.URISyntaxException;
import java.util.Enumeration;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class JmsQueueBrowseExample {
    public static void main(String[] args) throws URISyntaxException, Exception {
        Connection connection = null;
        try {
            // Producer
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                    "tcp://localhost:61616");
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(false,
                    Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue("browseQueue");
            MessageConsumer consumer = session.createConsumer(queue);
            connection.start();

            System.out.println("Browse through the elements in queue");
            QueueBrowser browser = session.createBrowser(queue);
            Enumeration e = browser.getEnumeration();
            //Multithreading here
            while (e.hasMoreElements()) {
                TextMessage message = (TextMessage) e.nextElement();
                System.out.println("Browse [" + message.getText() + "]");
            }
            System.out.println("Done");
            browser.close();

            session.close();
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

}

谢谢

最佳答案

除了 close 方法之外,JMS API 资源(例如 Session、MessageConsumer、QueueBrowser 等)不适合由多个控制线程使用,因此尝试同时迭代从 QueueBrowser 枚举返回的消息是可能导致的结果是错误。

JMS 规范增加了对 session 资源并发性的一些了解。

There are no restrictions on the number of threads that can use a Session object or those it creates. The restriction is that the resources of a Session should not be used concurrently by multiple threads. It is up to the user to insure that this concurrency restriction is met. The simplest way to do this is to use one thread. In the case of asynchronous delivery, use one thread for setup in stopped mode and then start asynchronous delivery. In more complex cases the user must provide explicit synchronization.

关于java - 以多线程方式浏览Jms Queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56837606/

相关文章:

Spring Boot Batch - 不包括 JobLauncherCommandLineRunner

mysql - Spring 批量推荐表索引

java - ActiveMQ:如何使旧消息出队?

java - 如何使用 Spring Batch 在作业中动态添加步骤

java - 如何修复列索引超出范围 SQLException

java - ClassCastException 但仍然编译

java - 使用名称而不是 PID 终止 Java 进程

java - 预登录 session ID?

java - 将 WebSphere MQ 类用于 Java 而不是 JMS 有什么好处?

java - 可以直接向队列发送消息请求吗?