要解决ActiveMQ多个消费者多个主题的性能问题,可以采用以下方法:
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class Consumer implements Runnable {
private String topicName;
private ConnectionFactory connectionFactory;
private Connection connection;
private Session session;
private MessageConsumer messageConsumer;
public Consumer(String topicName) {
this.topicName = topicName;
this.connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
}
public void run() {
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createTopic(topicName);
messageConsumer = session.createConsumer(destination);
MessageListener listener = new MessageListener() {
public void onMessage(Message message) {
try {
// 处理消息
System.out.println("Received message: " + message);
} catch (Exception e) {
e.printStackTrace();
}
}
};
messageConsumer.setMessageListener(listener);
} catch (Exception e) {
e.printStackTrace();
}
}
public void stop() throws JMSException {
if (connection != null) {
connection.close();
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
// 创建消费者线程,并提交给线程池处理
for (int i = 0; i < 5; i++) {
Consumer consumer = new Consumer("Topic" + i);
executorService.submit(consumer);
}
// 关闭线程池
executorService.shutdown();
}
}
使用上述方法,可以实现ActiveMQ多个消费者多个主题的高性能处理。同时,可以根据实际需求调整消费者线程数量和线程池大小,以达到最佳性能。