gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:43:51 24 4
gpt4 key购买 nike

我有一个浏览队列消息的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com