【发布时间】:2017-09-18 03:29:32
【问题描述】:
如何使用 ActiveMQ 中的持久连接/会话将消息排入不同队列?
我做了什么:
public class ActiveMQProducer {
private static final Logger LOGGER = Logger.getLogger(ActiveMQProducer.class);
private Connection connection;
private MessageProducer producer;
private Session session;
String activeMQConnection;
public ActiveMQProducer() throws ConfigurationException, JMSException {
activeMQConnection = ActiveMQPropertyManagerFactory.getInstance().getString("active.mq.url");
}
public void setupActiveMQ(String queueName) throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(activeMQConnection);
factory.setRejectedTaskHandler(new ThreadPoolExecutor.CallerRunsPolicy());
connection = factory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(queueName);
producer = session.createProducer(queue);
}
public void getConnection(String queueName) throws JMSException {
if (connection == null || session == null) {
Object object = new Object();
synchronized (object) {
setupActiveMQ(queueName);
}
}
}
public <T extends Serializable> T sendToActiveMQ(String queueName, T t) throws JMSException {
getConnection(queueName);
ObjectMessage message = session.createObjectMessage(t);
producer.send(message);
return null;
}
public void sendMessageToActiveMQ(String queueName, String message) throws JMSException {
getConnection(queueName);
TextMessage toSend = session.createTextMessage(message);
producer.send(toSend);
}
}
我已经意识到,通过使用它并将消息发送到不同的队列最终 ActiveMQ 会耗尽连接,因为我从未关闭连接或会话:
org.apache.activemq.transport.tcp.ExceededMaximumConnectionsException: Exceeded the maximum number of allowed client connections.
处理这个问题的正确方法是什么?我有大约 5 个队列我必须向其发送不同的消息,我是否应该打开一个新连接、入队并关闭连接,是否有办法保持会话/连接持久?
谢谢。
【问题讨论】: