JMS 池连接不支持同步接收

来源:互联网 发布:mx master mac 编辑:程序博客网 时间:2024/06/04 19:31

使用org.apache.activemq.pool.PooledConnection连接,发送消息时不支持同步消息接收:

/** * 使用连接池 */public void init(){try {ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, url);pooledConnectionFactory = new PooledConnectionFactory(connectionFactory);pooledConnectionFactory.setCreateConnectionOnStartup(true);pooledConnectionFactory.setMaxConnections(5);pooledConnectionFactory.setMaximumActiveSessionPerConnection(100);connection = pooledConnectionFactory.createConnection();System.out.println("2connection name:" + connection.getClass().getName());// 是生产和消费的一个单线程上下文。会话用于创建消息的生产者,消费者和消息。会话提供了一个事务性的上下文。session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 不支持事务// 目的地是客户用来指定他生产消息的目标还有他消费消息的来源的对象,两种消息传递方式:点对点和发布/订阅destination = session.createQueue(subject);// 会话创建消息的生产者将消息发送到目的地consumer = session.createConsumer(destination);} catch (Exception e) {e.printStackTrace();}}// 消费消息public void receiveMessage() throws JMSException, Exception {init();System.out.println("Consumer:->Begin listening...");// 开始监听TextMessage message = (TextMessage)consumer.receive();System.out.println("message:" + message.getText());close();}

直接使用org.apache.activemq.ActiveMQConnection,则可以接收同步消息。

// 初始化private void initialize() throws JMSException, Exception {// 连接工厂是用户创建连接的对象,这里使用的是ActiveMQ的ActiveMQConnectionFactory根据url,username和password创建连接工厂。ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, url);// 连接工厂创建一个jms connectiontry {connection = connectionFactory.createConnection();System.out.println("connection name:" + connection.getClass().getName());connection.start();} catch (Exception e) {if (connection != null)connection.close();System.exit(0);}// 是生产和消费的一个单线程上下文。会话用于创建消息的生产者,消费者和消息。会话提供了一个事务性的上下文。session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 不支持事务Session temp = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 不支持事务// 目的地是客户用来指定他生产消息的目标还有他消费消息的来源的对象,两种消息传递方式:点对点和发布/订阅destination = session.createQueue(subject);// 会话创建消息的生产者将消息发送到目的地consumer = session.createConsumer(destination);}// 消费消息public void receiveMessage2() throws JMSException, Exception {initialize();System.out.println("Consumer:->Begin listening...");// 开始监听TextMessage message = (TextMessage)consumer.receive();System.out.println("message:" + message.getText());close();}

解决该问题的要点:

在获取连接后,要开始它!

connection.start();  //对于PooledConnection和ActiveMQConnection均要求调用该方法。




0 0