jboss jms 实例

  最近温习了下EJB和JMS,整理了下思路,和大家分享下P2P和Pub/Sub的demo  ;JBoss 7 集成了HornetQ,JMS可以在HornetQ中间件运行,有时间在和大家分享关于HornetQ的文章。 

1.下载Jboss 7并配置运行环境 http://www.jboss.org/jbossas/downloads 
2.增加testjms用户(用以jms链接时使用),在jboss的bin目录下运行add-user.bat,如下: guest 一定要写。 
 
3.修改启动配置文件,使用standalone-full.xml启动jboss服务器 
Cmd代码   收藏代码
  1. $JBOSS_HOME$\bin>standalone.bat --server-config=standalone-full.xml  

4.例子:修改Jboss配置文件standalone-full.xml,找到hornetq-server节点,在该节点下的jms-destinations确定含有以下配置: 
Xml代码   收藏代码
  1. <jms-destinations>  
  2.                     <jms-queue name="testQueue">  
  3.                         <entry name="queue/test"/>  
  4.                         <entry name="java:jboss/exported/jms/queue/test"/>  
  5.                     </jms-queue>  
  6.                     <jms-topic name="ServerNotificationTopic">  
  7.                         <entry name="topic/ServerNotification"/>  
  8.                         <entry name="java:jboss/exported/jms/topic/ServerNotification"/>  
  9.                     </jms-topic>  
  10.                 </jms-destinations>  

客户端项目用eclipse集成jboss的 j2ee项目。runtime是jboss 7.
另外一定别忘了加入 external lib : jboss-client-7.1.0.Final.jar (JBOSS_HOME/bin/client) 
否则会报错:
javax.naming.NamingException: JBAS011843: Failed instantiate InitialContextFactory
 
 User: acs doesn't have permission='SEND' on address jms.queue.testQueue 权限错误,需要看看:
“jboss-home\stabdalone\configuration\application-roles.properties” 
加一句 testjms=guest
 
其他错误参见:
http://www.techartifact.com/blogs/2012/10/jboss-as-7-setting-up-hornetq-jms.html#sthash.OLzvKFO6.dpbs
 
在测试中遇到收不到消息。可以在控制台查看对应的queue有多少个comsumer。我的代码由于开始没有写consumer.close(). 导致接收完后虽然函数结束没有再调用receve阻塞方法了,但consumer一直存在。从jboss7的管理页面可以看到有好几个consumer。导致再次发送的消息还会被它吃掉。整了一天不断测试才搞明白。
 public Object Receive(String filter, long timeoutReceive) throws JMSException {
        System.out.println ("======enter Receive===" );
        System.out.println("Creating cosumer with filter: " + filter );
        MessageConsumer consumer = queuesession.createConsumer(queue, filter);
        
        Message mrcv = null;
        System.out.println("receive message with timeout="+timeoutReceive);
        mrcv = consumer.receive(timeoutReceive);
        if (mrcv != null) {
            try {
                System.out.println("RCV1: " + mrcv.getJMSCorrelationID());
                System.out.println("====== consumer.close();.=====");
                consumer.close();
                return ((ObjectMessage) mrcv).getObject();;
            } catch (MessageFormatException e) {
                System.out.println("MessageFormatException: " + e.getMessage());
                mrcv.acknowledge();
            }
        } else {
            System.out.println("======receive message time out.=====");
        }
        consumer.close();
        return null;
    }
View Code

 


P2P demo 
Jmsproducer代码  
  1. package org.jboss.as.quickstarts.jms;  
  2.   
  3. import java.util.concurrent.CountDownLatch;  
  4. import java.util.concurrent.TimeUnit;  
  5. import java.util.logging.Logger;  
  6. import java.util.Properties;  
  7.   
  8. import javax.jms.Connection;  
  9. import javax.jms.ConnectionFactory;  
  10. import javax.jms.Destination;  
  11. import javax.jms.MessageConsumer;  
  12. import javax.jms.MessageProducer;  
  13. import javax.jms.Session;  
  14. import javax.jms.TextMessage;  
  15. import javax.naming.Context;  
  16. import javax.naming.InitialContext;  
  17.   
  18. public class JMSProducer {  
  19.     private static final Logger log = Logger.getLogger(JMSProducer.class.getName());  
  20.   
  21.     // Set up all the default values  
  22.     private static final String DEFAULT_MESSAGE = "Hello, World!";  
  23.     private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory";  
  24.     private static final String DEFAULT_DESTINATION = "jms/queue/test";  
  25.     private static final String DEFAULT_MESSAGE_COUNT = "1";  
  26.     private static final String DEFAULT_USERNAME = "testjms";  
  27.     private static final String DEFAULT_PASSWORD = "123456";  
  28.     private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";  
  29.     private static final String PROVIDER_URL = "remote://localhost:4447";  
  30.   
  31.     public static void main(String[] args) throws Exception {  
  32.   
  33.         ConnectionFactory connectionFactory = null;  
  34.         Connection connection = null;  
  35.         Session session = null;  
  36.         MessageProducer producer = null;  
  37.         Destination destination = null;  
  38.         TextMessage message = null;  
  39.         Context context = null;  
  40.   
  41.         try {  
  42.             // Set up the context for the JNDI lookup  
  43.             final Properties env = new Properties();  
  44.             env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);  
  45.             env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));  
  46.             env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));  
  47.             env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));  
  48.             context = new InitialContext(env);  
  49.   
  50.             // Perform the JNDI lookups  
  51.             String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);  
  52.             log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");  
  53.             connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);  
  54.             log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");  
  55.   
  56.             String destinationString = System.getProperty("destination", DEFAULT_DESTINATION);  
  57.             log.info("Attempting to acquire destination \"" + destinationString + "\"");  
  58.             destination = (Destination) context.lookup(destinationString);  
  59.             log.info("Found destination \"" + destinationString + "\" in JNDI");  
  60.   
  61.             // Create the JMS connection, session, producer, and consumer  
  62.             connection = connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD));  
  63.             session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);  
  64.             producer = session.createProducer(destination);  
  65.             connection.start();  
  66.   
  67.             int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT));  
  68.             String content = System.getProperty("message.content", DEFAULT_MESSAGE);  
  69.   
  70.             log.info("Sending " + count + " messages with content: " + content);  
  71.   
  72.              
  73.             // Send the specified number of messages  
  74.             for (int i = 0; i < count; i++) {  
  75.                 message = session.createTextMessage(content);  
  76.                 producer.send(message);  
  77.             }  
  78.   
  79.             //等待30秒退出  
  80.             CountDownLatch latch = new CountDownLatch(1);         
  81.             latch.await(30, TimeUnit.SECONDS);  
  82.               
  83.         } catch (Exception e) {  
  84.             log.severe(e.getMessage());  
  85.             throw e;  
  86.         } finally {  
  87.             if (context != null) {  
  88.                 context.close();  
  89.             }  
  90.   
  91.             // closing the connection takes care of the session, producer, and consumer  
  92.             if (connection != null) {  
  93.                 connection.close();  
  94.             }  
  95.         }  
  96.     }  
  97. }  



Jmsconsumer代码   收藏代码
  1. package org.jboss.as.quickstarts.jms;  
  2.   
  3. import java.util.concurrent.CountDownLatch;  
  4. import java.util.concurrent.TimeUnit;  
  5. import java.util.logging.Logger;  
  6. import java.util.Properties;  
  7.   
  8. import javax.jms.Connection;  
  9. import javax.jms.ConnectionFactory;  
  10. import javax.jms.Destination;  
  11. import javax.jms.MessageConsumer;  
  12. import javax.jms.MessageProducer;  
  13. import javax.jms.Session;  
  14. import javax.jms.TextMessage;  
  15. import javax.naming.Context;  
  16. import javax.naming.InitialContext;  
  17.   
  18. public class JMSConsumer {  
  19.     private static final Logger log = Logger.getLogger(JMSConsumer.class.getName());  
  20.   
  21.     // Set up all the default values  
  22.   
  23.     private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory";  
  24.     private static final String DEFAULT_DESTINATION = "jms/queue/test";  
  25.     private static final String DEFAULT_USERNAME = "testjms";  
  26.     private static final String DEFAULT_PASSWORD = "123456";  
  27.     private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";  
  28.     private static final String PROVIDER_URL = "remote://localhost:4447";  
  29.   
  30.     public static void main(String[] args) throws Exception {  
  31.   
  32.         ConnectionFactory connectionFactory = null;  
  33.         Connection connection = null;  
  34.         Session session = null;  
  35.         MessageConsumer consumer = null;  
  36.         Destination destination = null;  
  37.         TextMessage message = null;  
  38.         Context context = null;  
  39.   
  40.         try {  
  41.             // Set up the context for the JNDI lookup  
  42.             final Properties env = new Properties();  
  43.             env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);  
  44.             env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));  
  45.             env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));  
  46.             env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));  
  47.             context = new InitialContext(env);  
  48.   
  49.             // Perform the JNDI lookups  
  50.             String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);  
  51.             log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");  
  52.             connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);  
  53.             log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");  
  54.   
  55.             String destinationString = System.getProperty("destination", DEFAULT_DESTINATION);  
  56.             log.info("Attempting to acquire destination \"" + destinationString + "\"");  
  57.             destination = (Destination) context.lookup(destinationString);  
  58.             log.info("Found destination \"" + destinationString + "\" in JNDI");  
  59.           
  60.             // Create the JMS connection, session, producer, and consumer  
  61.             connection = connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD));  
  62.             session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);  
  63.             consumer = session.createConsumer(destination);  
  64.             connection.start();  
  65.   
  66.             //等待30秒退出  
  67.             CountDownLatch latch = new CountDownLatch(1);         
  68.                           
  69.             // Then receive the same number of messaes that were sent  
  70.            while(message == null) {  
  71.                 log.info("----receive message");  
  72.                 message = (TextMessage) consumer.receive(5000);      
  73.                 latch.await(1, TimeUnit.SECONDS);  
  74.            }  
  75.            log.info("====Received message with content " + message.getText());  
  76.              
  77.         } catch (Exception e) {  
  78.             log.severe(e.getMessage());  
  79.             throw e;  
  80.         } finally {  
  81.             if (context != null) {  
  82.                 context.close();  
  83.             }  
  84.   
  85.             // closing the connection takes care of the session, producer, and consumer  
  86.             if (connection != null) {  
  87.                 connection.close();  
  88.             }  
  89.         }  
  90.     }  
  91. }  




Pub/Sub demo 
Jmspub代码   收藏代码
  1. package com.lym.jms;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.util.Properties;  
  7.   
  8. import javax.jms.Destination;  
  9. import javax.jms.JMSException;  
  10. import javax.jms.Session;  
  11. import javax.jms.TextMessage;  
  12. import javax.naming.Context;  
  13. import javax.naming.InitialContext;  
  14. import javax.naming.NamingException;  
  15.   
  16. public class JMSPub {  
  17.     private static final String DEFAULT_USERNAME = "testjms";  
  18.     private static final String DEFAULT_PASSWORD = "123456";  
  19.     private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";  
  20.     private static final String PROVIDER_URL = "remote://localhost:4447";  
  21.         
  22.     /**  
  23.      * @param args  
  24.      * @throws NamingException   
  25.      * @throws JMSException   
  26.      * @throws IOException   
  27.      */  
  28.     public static void main(String[] args) throws NamingException, JMSException, IOException {  
  29.         final Properties env = new Properties();  
  30.         env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);  
  31.         env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));  
  32.         env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));  
  33.         env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));  
  34.         InitialContext context = new InitialContext(env);  
  35.   
  36.   
  37.         // 1) lookup connection factory (local JNDI lookup, no credentials required)  
  38.         javax.jms.ConnectionFactory cf = (javax.jms.ConnectionFactory)context.lookup("jms/RemoteConnectionFactory");  
  39.            
  40.         // 2) create a connection to the remote provider  
  41.         javax.jms.Connection connection = cf.createConnection(DEFAULT_USERNAME, DEFAULT_PASSWORD);  
  42.           
  43.         // 3) create session session  
  44.         boolean transacted = false;  
  45.         javax.jms.Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);  
  46.            
  47.         /**  
  48.          * 在standalone-full.xml中找到  
  49.          * <subsystem xmlns="urn:jboss:domain:messaging:1.1">  
  50.          * 节点下找到<jms-destinations>节点,增加  
  51.          *  <jms-topic name="ServerNotificationTopic">  
  52.                 <entry name="topic/ServerNotification"/>  
  53.                 <entry name="java:jboss/exported/jms/topic/ServerNotification"/>  
  54.             </jms-topic>  
  55.          */  
  56.         // 4) "create" the queue/topic (using the topic name - not JNDI)  
  57.         //javax.jms.Topic topic = session.createTopic("ServerNotificationTopic");  
  58.         javax.jms.Topic topic = (javax.jms.Topic)context.lookup("jms/topic/ServerNotification");          
  59.         // 5) create producer  
  60.         //javax.jms.MessageProducer producer = session.createProducer(topic);  
  61.               
  62.         Destination destination = (Destination) context.lookup("jms/topic/ServerNotification");  
  63.         javax.jms.MessageProducer producer = session.createProducer(destination);  
  64.           
  65.         BufferedReader msgStream = new BufferedReader(new InputStreamReader(    
  66.                 System.in));    
  67.         String line = null;    
  68.         boolean quitNow = false;    
  69.         do {    
  70.             System.out.print("Enter message (\"quit\" to quit): ");    
  71.             line = msgStream.readLine();    
  72.             if (line != null && line.trim().length() != 0) {    
  73.   
  74.                 // 6) create message  
  75.                 TextMessage textMessage = session.createTextMessage();  
  76.                 textMessage.setText(line);  
  77.                   
  78.                 // 7) send message  
  79.                 producer.send(textMessage);  
  80.                   
  81.                 quitNow = line.equalsIgnoreCase("quit");    
  82.             }    
  83.         } while (!quitNow);    
  84.           
  85.           
  86.     }  
  87.   
  88. }  



Jmssub代码   收藏代码
  1. package com.lym.jms;  
  2.   
  3. import java.util.Properties;  
  4. import java.util.concurrent.CountDownLatch;  
  5. import java.util.concurrent.TimeUnit;  
  6.   
  7. import javax.jms.JMSException;  
  8. import javax.jms.Session;  
  9. import javax.jms.TextMessage;  
  10. import javax.naming.Context;  
  11. import javax.naming.InitialContext;  
  12. import javax.naming.NamingException;  
  13.   
  14. public class JMSSub {  
  15.   
  16.     private static final String DEFAULT_USERNAME = "testjms";  
  17.     private static final String DEFAULT_PASSWORD = "123456";  
  18.     private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";  
  19.     private static final String PROVIDER_URL = "remote://localhost:4447";  
  20.       
  21.     /**  
  22.      * @param args  
  23.      * @throws NamingException   
  24.      * @throws JMSException   
  25.      * @throws InterruptedException   
  26.      */  
  27.     public static void main(String[] args) throws NamingException, JMSException, InterruptedException {  
  28.         final Properties env = new Properties();  
  29.         env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);  
  30.         env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));  
  31.         env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));  
  32.         env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));  
  33.         InitialContext context = new InitialContext(env);  
  34.   
  35. //      javax.jms.Topic topic = (javax.jms.Topic)context.lookup("jms/topic/ServerNotification");           
  36.   
  37.         // 1) lookup connection factory (local JNDI lookup, no credentials required)  
  38.         javax.jms.ConnectionFactory cf = (javax.jms.ConnectionFactory)context.lookup("jms/RemoteConnectionFactory");  
  39.            
  40.         // 2) create a connection to the remote provider  
  41.         javax.jms.Connection connection = cf.createConnection(DEFAULT_USERNAME, DEFAULT_PASSWORD);  
  42.                   
  43.         // 3) create session session  
  44.         boolean transacted = false;  
  45.         javax.jms.Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);  
  46.            
  47.         // 4) "create" the queue/topic (using the topic name - not JNDI)  
  48.         javax.jms.Topic topic = session.createTopic("ServerNotificationTopic");  
  49.            
  50.         // 5) create consumer  
  51.         javax.jms.MessageConsumer consumer = session.createConsumer(topic); // messageSelector is optional  
  52.            
  53.         // 6) set listener  
  54.         consumer.setMessageListener(new javax.jms.MessageListener() {  
  55.           public void onMessage(javax.jms.Message message)  
  56.           {  
  57.             try {  
  58.                 TextMessage tm = (TextMessage)message;  
  59.                   
  60.                 System.out.println("received message content: "+tm.getText().toString());  
  61.                 System.out.println("getJMSDestination: "+tm.getJMSDestination());  
  62.                 System.out.println("getJMSReplyTo: "+tm.getJMSReplyTo());  
  63.                 System.out.println("getJMSMessageID: "+tm.getJMSMessageID());  
  64.                 System.out.println("getJMSRedelivered: "+tm.getJMSRedelivered());  
  65.                   
  66.             } catch (JMSException e) {  
  67.                 // TODO Auto-generated catch block  
  68.                 e.printStackTrace();  
  69.             }    
  70.           }  
  71.         });  
  72.            
  73.         // 7) listen for messages (start the connection)  
  74.         connection.start();  
  75.           
  76.         //等待30秒退出  
  77.         CountDownLatch latch = new CountDownLatch(1);         
  78.         latch.await(30, TimeUnit.SECONDS);  
  79.           
  80.           
  81.     }  
  82.   
  83.   
  84. }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值