SimpleQueueReceiver.java
资源名称:某公司的java培训教材 [点击查看]
上传用户:dinglihq
上传日期:2013-02-04
资源大小:99958k
文件大小:3k
源码类别:
Java编程
开发平台:
Java
- package demojms;
- /*
- * @(#)SimpleQueueReceiver.java
- */
- import javax.jms.*;
- import javax.naming.*;
- import java.util.*;
- public class SimpleQueueReceiver {
- public static void main(String[] args) {
- String queueName = null;
- Context jndiContext = null;
- QueueConnectionFactory queueConnectionFactory = null;
- QueueConnection queueConnection = null;
- QueueSession queueSession = null;
- Queue queue = null;
- QueueReceiver queueReceiver = null;
- TextMessage message = null;
- /*
- * 从命令行读queue并显示
- */
- /*if (args.length != 1) {
- System.out.println("Usage: java SimpleQueueReceiver " +
- "<queue-name>");
- System.exit(1);
- }*/
- //queueName = new String(args[0]);
- queueName = "TheQue";
- System.out.println("Queue name is " + queueName);
- /*
- * 如果不存在JNDI InitialContext对象,就创建一个
- */
- try {
- Properties properties = null;
- String url = "t3://127.0.0.1:7001";
- properties = new Properties();
- properties.put(Context.INITIAL_CONTEXT_FACTORY,
- "weblogic.jndi.WLInitialContextFactory");
- properties.put(Context.PROVIDER_URL, url);
- jndiContext = new InitialContext(properties);
- }
- catch (NamingException e) {
- System.out.println("Could not create JNDI " +
- "context: " + e.toString());
- System.exit(1);
- }
- /*
- * 寻找connection factory和queue,如果两者读不存在,则退出
- */
- try {
- queueConnectionFactory = (QueueConnectionFactory)
- jndiContext.lookup("QueueConnectionFactory1");
- //System.out.println(jndiContext);
- queue = (Queue) jndiContext.lookup("TheQue");
- }
- catch (NamingException e) {
- System.out.println("JNDI lookup failed: "
- + e.toString());
- System.exit(1);
- }
- /*
- * 创建一个connection,再从connection创建session
- * 创建receiver和文本消息,从queue接收所有的消息
- * 最后,关闭connection
- */
- try {
- queueConnection =
- queueConnectionFactory.createQueueConnection();
- queueSession =
- queueConnection.createQueueSession(false,
- Session.AUTO_ACKNOWLEDGE);
- queueReceiver = queueSession.createReceiver(queue);
- queueConnection.start();
- while (true) {
- Message m = queueReceiver.receive(1);
- if (m != null) {
- if (m instanceof TextMessage) {
- message = (TextMessage) m;
- System.out.println("Reading message: " +
- message.getText());
- }
- else {
- break;
- }
- }
- }
- }
- catch (JMSException e) {
- System.out.println("Exception occurred: " +
- e.toString());
- }
- finally {
- if (queueConnection != null) {
- try {
- queueConnection.close();
- }
- catch (JMSException e) {}
- }
- }
- }
- }