JavaEE知识整理系列(六)JMS .

 DIY例子

使用JMS不仅能发送(send)/发布(publish)消息,也能获得(receive)/订阅(subscribe)的消息,消息的发送(send)/发布(publish)和(receive)/订阅(subscribe)和JBOSS的相对位置是无关的,这个在实际应用中非常有用。在C/S架构的软件中,一般S端部署了JBOSS,作为JMS的publisher,而C端一般是Java程序,作为JMS的subscriber。这里以topic的形式举例说明,注:下面以可序列化的Map作为消息传输载体。

 

  1. import org.martin.common.communication.jms.JmsService;  
  2. import org.martin.common.communication.jms.JmsServiceImpl;  
  3.   
  4. public class ServiceAccess  
  5. {  
  6.     public static JmsService  getJMSService(){  
  7.         return new JmsServiceImpl();  
  8.     }  
  9. }  
  10. package org.martin.common.communication.jms;  
  11. public class Constants  
  12. {  
  13.     public static final int DEST_TYPE_TOPIC=1;  
  14.     public static final int DEST_TYPE_QUEUE=2;  
  15.     public static final int DEST_OPER_ADD=1;  
  16.     public static final int DEST_OPER_DELETE=2;  
  17. }  
  18. public class JmsAsyncReceiver  
  19. {  
  20.   
  21.     private TopicConnection topicConnection;  
  22.     private TopicSession    topicSession;  
  23.     private TopicSubscriber topicSubscriber;  
  24.     private Topic           topic;  
  25.       
  26.     @SuppressWarnings("unchecked")  
  27.     public JmsAsyncReceiver(String factoryJNDI, String topicJNDI,  
  28.          MessageListener messagelistener) throws JMSException,NamingException  
  29.     {  
  30.         Hashtable props = new Hashtable();  
  31.         props.put(Context.INITIAL_CONTEXT_FACTORY,  
  32.                         "org.jnp.interfaces.NamingContextFactory");  
  33.         props.put(Context.PROVIDER_URL, "localhost:1099");  
  34.         props.put("java.naming.rmi.security.manager""yes");  
  35.         props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming");  
  36.         Context context = new InitialContext(props);  
  37.         TopicConnectionFactory topicFactory = (TopicConnectionFactory)  
  38.                                           context.lookup(factoryJNDI);  
  39.         topicConnection = topicFactory.createTopicConnection();  
  40.         topicSession = topicConnection.createTopicSession(false,  
  41.                                              Session.AUTO_ACKNOWLEDGE);  
  42.         topic = (Topic) context.lookup(topicJNDI);  
  43.         topicSubscriber = topicSession.createSubscriber(topic);  
  44.         topicSubscriber.setMessageListener(messagelistener);  
  45.         System.out.println("AsyncReceiver subscribed to topic: " + topicJNDI);  
  46.         topicConnection.start();  
  47.     }  
  48.       
  49.     public void close() throws JMSException  
  50.     {  
  51.         topicSession.close();  
  52.         topicConnection.close();  
  53.     }  
  54. }  
  55. public class JmsHelper  
  56. {  
  57.     public static void addDestination(String destName){  
  58.         try{  
  59.             invokeViaMBean("createTopic", destName);  
  60.         }catch(Exception e){  
  61.             //e.printStackTrace();   
  62.             try{  
  63.                 invokeViaMBeanInDiffJVM("createTopic",  destName);  
  64.             }catch(Exception e1){  
  65.                 //e1.printStackTrace();   
  66.             }  
  67.         }  
  68.     }  
  69.       
  70.     private static void invokeViaMBean(String method, String destName) throws Exception  
  71.     {  
  72.         MBeanServer server = (MBeanServer) MBeanServerFactory.findMBeanServer(null)  
  73.                         .iterator().next();  
  74.         server.invoke(new ObjectName("jboss.mq""service""DestinationManager"), method,  
  75.                         new Object[] { destName }, new String[] { "java.lang.String" });  
  76.     }  
  77.       
  78.     private static void invokeViaMBeanInDiffJVM(String method, String destName)throws Exception{  
  79.         Context context;  
  80.         Hashtable <String, String> jndi = new Hashtable <String, String>();  
  81.         jndi.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");  
  82.         jndi.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");  
  83.         jndi.put(Context.PROVIDER_URL, "localhost:1099");  
  84.   
  85.         context = new InitialContext(jndi);  
  86.         MBeanServerConnection server = (MBeanServerConnection) context.lookup("jmx/invoker/RMIAdaptor");  
  87.         server.invoke(new ObjectName("jboss.mq:service=DestinationManager"),  
  88.                         method,  
  89.                       new Object[] {destName, "topic/" + destName},  
  90.                       new String[] {"java.lang.String""java.lang.String"});  
  91.     }  
  92. }  
  93. public interface JmsReceiveListener  
  94. {  
  95.     void onMessage(Object msg);  
  96. }  
  97. public class JmsReceiveScheduler implements MessageListener  
  98. {  
  99.     private JmsAsyncReceiver regInfo;  
  100.     private ConcurrentHashMap<String, JmsReceiveListener> listenerMap   
  101.                 = new ConcurrentHashMap<String, JmsReceiveListener>();  
  102.     private String destination=null;  
  103.       
  104.     public JmsReceiveScheduler(String destination)   
  105.     throws JMSException, NamingException  
  106.     {  
  107.         this.destination=destination;  
  108.         JmsService service=ServiceAccess.getJMSService();  
  109.         regInfo = service.registAsyncReceive(Constants.DEST_TYPE_TOPIC,   
  110.                         this.destination, this);  
  111.     }  
  112.       
  113.     public  void registerListener(String clientID, JmsReceiveListener listener)  
  114.     {  
  115.         listenerMap.put(clientID, listener);  
  116.     }  
  117.       
  118.     public  void unregisterListener(String id)  
  119.     {  
  120.         listenerMap.remove(id);  
  121.     }  
  122.       
  123.     public  void close() throws JMSException  
  124.     {  
  125.         regInfo.close();  
  126.     }  
  127.   
  128.     @SuppressWarnings("unchecked")  
  129.     public void onMessage(Message msgIn)  
  130.     {  
  131.         ObjectMessage objMsg = (ObjectMessage) msgIn;  
  132.         Map map=null;  
  133.         try{  
  134.             map = (HashMap) objMsg.getObject();  
  135.         }catch(JMSException e){  
  136.             e.printStackTrace();  
  137.         }  
  138.         String clientID = (String) map.get("CLIENT_ID");  
  139.         JmsReceiveListener listener = listenerMap.get(clientID);  
  140.         if(listener != null)  
  141.         {  
  142.             listener.onMessage(map.get("DATA"));  
  143.         }  
  144.     }  
  145. }  
  146. public class JmsSender  
  147. {  
  148.     private TopicConnection topicConnection;  
  149.     private TopicSession    topicSession;  
  150.     private TopicPublisher  topicPublisher;  
  151.     private Topic           topic;  
  152.       
  153.     @SuppressWarnings("unchecked")  
  154.     public JmsSender(String factoryJNDI, String topicJNDI)   
  155.            throws JMSException,NamingException  
  156.     {  
  157.         Hashtable props = new Hashtable();  
  158.         props.put(Context.INITIAL_CONTEXT_FACTORY,  
  159.                         "org.jnp.interfaces.NamingContextFactory");  
  160.         props.put(Context.PROVIDER_URL, "localhost:1099");  
  161.         props.put("java.naming.rmi.security.manager""yes");  
  162.         props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming");  
  163.         Context context = new InitialContext(props);  
  164.         TopicConnectionFactory topicFactory = (TopicConnectionFactory) context  
  165.                         .lookup(factoryJNDI);  
  166.         topicConnection = topicFactory.createTopicConnection();  
  167.         topicSession = topicConnection  
  168.                         .createTopicSession(false, Session.AUTO_ACKNOWLEDGE);  
  169.           
  170.         topic = (Topic) context.lookup(topicJNDI);  
  171.         topicPublisher = topicSession.createPublisher(topic);  
  172.           
  173.     }  
  174.       
  175.     @SuppressWarnings("unchecked")  
  176.     public void publish(Map msg) throws JMSException  
  177.     {  
  178.         ObjectMessage  message = topicSession.createObjectMessage();  
  179.         message.setObject((Serializable) msg);  
  180.         topicPublisher.publish(topic, message);   
  181.     }  
  182.       
  183.     public void close() throws JMSException  
  184.     {  
  185.         topicSession.close();  
  186.         topicConnection.close();  
  187.     }  
  188.   
  189. }  
  190. public class JmsSenderWrapped  
  191. {  
  192.   
  193.     private static JmsSender sender;  
  194.   
  195.     public JmsSenderWrapped(String destination)   
  196.     throws JMSException, NamingException{  
  197.         JmsService  jmsService = ServiceAccess.getJMSService();  
  198.         sender = jmsService.getSender(Constants.DEST_TYPE_TOPIC, destination);  
  199.     }  
  200.   
  201.     @SuppressWarnings("unchecked")  
  202.     public  void sendJMSMessage(String clientID, Serializable dataIn)   
  203.     throws JMSException  
  204.     {  
  205.         Map map = new HashMap();  
  206.         map.put("CLIENT_ID", clientID);  
  207.         map.put("DATA", dataIn);  
  208.         sender.publish( map);  
  209.     }  
  210.       
  211.     public void close() throws JMSException{  
  212.         sender.close();  
  213.     }  
  214. }  
  215. public interface JmsService  
  216. {  
  217.     JmsAsyncReceiver registAsyncReceive(int destType,String destination,  
  218.        MessageListener listener) throws JMSException, NamingException;  
  219.   
  220.     JmsSender getSender(int destType, String destination) throws JMSException,   
  221.     NamingException;  
  222.       
  223.     public void operDestination(int operType,int destType, String destination);  
  224. }  
  225. public class JmsServiceImpl implements JmsService  
  226. {  
  227.     public JmsAsyncReceiver registAsyncReceive(int destType, String destination,  
  228.     MessageListener listener) throws JMSException, NamingException  
  229.     {  
  230.         if(destType==Constants.DEST_TYPE_TOPIC){  
  231.             JmsAsyncReceiver receivere = new JmsAsyncReceiver  
  232.             ("TopicConnectionFactory","topic/"+destination, listener);  
  233.             return receivere;  
  234.         }else if(destType==Constants.DEST_TYPE_QUEUE){  
  235.               
  236.         }  
  237.         return null;  
  238.     }  
  239.   
  240.     public JmsSender getSender(int destType, String destination)   
  241.     throws JMSException, NamingException  
  242.     {  
  243.         if(destType==Constants.DEST_TYPE_TOPIC){  
  244.             JmsSender sender=new JmsSender  
  245.             ( "ConnectionFactory",  "topic/"+destination);  
  246.             return sender;  
  247.         }  
  248.         return null;  
  249.     }  
  250.   
  251.     public void operDestination(int operType,int destType, String destination)  
  252.     {  
  253.         if(destType==Constants.DEST_TYPE_TOPIC){  
  254.             if(operType==Constants.DEST_OPER_ADD){  
  255.                 JmsHelper.addDestination(destination);  
  256.             }  
  257.         }  
  258.           
  259.     }    
  260.       
  261. }  
  262. public class ReceiveTest  
  263. {  
  264.     public static void main(String[]args){  
  265.         String destName="MyTestDestination";  
  266.         String clientName="MyTClientName";  
  267.         JmsService service=ServiceAccess.getJMSService();  
  268.         service.operDestination(Constants.DEST_OPER_ADD,  
  269.                         Constants.DEST_TYPE_TOPIC, destName);  
  270.           
  271.         JmsReceiveScheduler schedul=null;  
  272.         try{  
  273.             schedul=new JmsReceiveScheduler(destName);  
  274.         }catch(JMSException e){  
  275.             e.printStackTrace();  
  276.         }catch(NamingException e){  
  277.             e.printStackTrace();  
  278.         }  
  279.         schedul.registerListener(clientName, new JmsReceiveListener(){  
  280.   
  281.             public void onMessage(Object msg)  
  282.             {  
  283.                 System.out.println(msg);  
  284.             }   
  285.         });  
  286.     }  
  287. }  
  288. public class SendTest  
  289. {  
  290.     public static void main(String[]args){  
  291.         String destName="MyTestDestination";  
  292.         String clientName="MyTClientName";  
  293.         JmsService service=ServiceAccess.getJMSService();  
  294.         service.operDestination(Constants.DEST_OPER_ADD,  
  295.                         Constants.DEST_TYPE_TOPIC, destName);  
  296.           
  297.         JmsSenderWrapped send=null;  
  298.         try{  
  299.             send=new JmsSenderWrapped(destName);  
  300.         }catch(JMSException e){  
  301.             e.printStackTrace();  
  302.         }catch(NamingException e){  
  303.             e.printStackTrace();  
  304.         }  
  305.         for(int i=0;i<10;i++){  
  306.             try{  
  307.                 send.sendJMSMessage(clientName, "count:"+i);  
  308.             }catch(JMSException e){  
  309.                 e.printStackTrace();  
  310.             }  
  311.         }  
  312.     }  
  313. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值