/** * Creates all the necessary objects for receiving messages from a JMS queue. * * @param ctx JNDI initial context * @param queueName name of queue * @exception NamingException if operation cannot be performed * @exception JMSException if JMS fails to initialize due to internal error */ public void init(Context ctx, String queueName) throws NamingException, JMSException { qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY); qcon = qconFactory.createQueueConnection(); qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queue = (Queue) ctx.lookup(queueName); qreceiver = qsession.createReceiver(queue); qreceiver.setMessageListener(this); qcon.start(); }
public QLender(String queuecf, String requestQueue) { try { // Connect to the provider and get the JMS connection Context ctx = new InitialContext(); QueueConnectionFactory qFactory = (QueueConnectionFactory) ctx.lookup(queuecf); qConnect = qFactory.createQueueConnection(); // Create the JMS Session qSession = qConnect.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); // Lookup the request queue requestQ = (Queue) ctx.lookup(requestQueue); // Now that setup is complete, start the Connection qConnect.start(); // Create the message listener QueueReceiver qReceiver = qSession.createReceiver(requestQ); qReceiver.setMessageListener(this); System.out.println("Waiting for loan requests..."); } catch (JMSException jmse) { jmse.printStackTrace(); System.exit(1); } catch (NamingException jne) { jne.printStackTrace(); System.exit(1); } }
@Test public void receiver() throws Exception { QueueConnection connection = null; QueueSession session = null; try { // 创建链接工厂 QueueConnectionFactory factory = new ActiveMQConnectionFactory( ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL); // 通过工厂创建一个连接 connection = factory.createQueueConnection(); // 启动连接 connection.start(); // 创建一个session会话 session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); // 创建一个消息队列 javax.jms.Queue queue = session.createQueue(TARGET); // 创建消息制作者 javax.jms.QueueReceiver receiver = session.createReceiver(queue); receiver.setMessageListener( new MessageListener() { public void onMessage(Message msg) { if (msg != null) { // MapMessage map = (MapMessage) msg; try { System.out.println(msg.getStringProperty("text")); // System.out.println(map.getLong("time") + "接收#" + // map.getString("text")); } catch (JMSException e) { e.printStackTrace(); } } } }); // 休眠100ms再关闭 Thread.sleep(1000 * 100); // 提交会话 session.commit(); } catch (Exception e) { throw e; } finally { // 关闭释放资源 if (session != null) { session.close(); } if (connection != null) { connection.close(); } } }