ITeye博客

Jms基础知识整理

houzi · 2009-05-19 16:36 · JAVA · Markdown

开始文章之前先澄清几个概念

什么是消息
消息是一个用于在组件和应用程序之间通讯的的方法。消息之间的传递是点对点的。任何终端之间都可以相互接受和发送消息。并且每个终端都必须遵守如下的规则
 -> 创建消息 -> 发送消息 -> 接收消息 -> 读取消息

为什么要使用消息
理由很简单,消息是一个分布式的低耦合通讯方案。A发送一个消息到一个agent ,B作为接受者去agent上获取消息。但是A,B不需要同时到agent上去注册。agent作为一个中转为A,B提供搞效率的通讯服务。

开发者的关注点
走到这里,我也不想去解释jms spec上那些抽象且复杂的概念了,说的很白,1年多了我自己也没弄懂是个什么东西,也没时间从头到尾去仔细的看,同时我认为没必要,我所关注的是如何让jms跑起来,并且工作正常,所以spec只是个字典,当我需要用的时候才去查。

开发者的jms环境
遵守简单明了的原则,所谓jms环境只是2个对象
1> ConnectionFactory
2> Destination
通常Provider会提供JNDI的对象获取,具体方法可以去Privider的网站上搜索jndi support

下面我以jbossMq为介质跑一个简单的jms,为了保证jms的本质清晰,我没有使用jbossMq的Api,而是直接调用的jms Api.

java 代码

 

  1. package  com.javaeye.jms.jboss;
  2. import  javax.jms.Connection;
  3. import  javax.jms.ConnectionFactory;
  4. import  javax.jms.Destination;
  5. import  javax.jms.JMSException;
  6. import  javax.jms.MessageConsumer;
  7. import  javax.jms.MessageProducer;
  8. import  javax.jms.Queue;
  9. import  javax.jms.QueueSender;
  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. public   class  JbossNativeJmsImpl {
  16. /**
  17. * @author zuly
  18. *
  19. * following jms ptp domain, use an simple text message to test
  20. *
  21. * A jms ptp sender will following the steps below!
  22. *     1> get an ConnectionFactory use JNDI Lookup Or Initial it yourself
  23. *     2> use this ConnectionFactory to start a jms connection
  24. *        [spec to jms 1.1 api to get the main idea of it ]
  25. *     3> use connection to create a jms session
  26. *     4> get a queue destination / messege agent
  27. *     5> start the Producer[jms1.1 spec] by a session
  28. *     6> get messege Object or initial it yourself by implements the messegeor
  29. *        it's sub interfaces
  30. *     7> call sender or send it selfing
  31. *     8> finallized the connection object or it will throw a warning to you!
  32. *
  33. * @param messege
  34. * @throws NamingException
  35. * @throws JMSException
  36. */
  37. public   void  sendingProcessing(String messege)  throws  NamingException, JMSException{
  38. Context ctx = new  InitialContext();
  39. ConnectionFactory cf = (ConnectionFactory) ctx.lookup("java:JmsXA" );
  40. Connection conn = cf.createConnection();
  41. Session session = conn.createSession(false , Session.AUTO_ACKNOWLEDGE);
  42. Destination dest = (Queue) ctx.lookup("queue/A" );
  43. MessageProducer msgp = session.createProducer(dest);
  44. QueueSender sender = (QueueSender) msgp;
  45. TextMessage msg = session.createTextMessage();
  46. msg.setText(messege);
  47. sender.send(msg);
  48. conn.close();
  49. }
  50. /**
  51. * @author zuly
  52. *
  53. * following jms ptp domain, use an simple text message to test
  54. *
  55. * A jms ptp retriver will following the steps below!
  56. *     1> get an ConnectionFactory use JNDI Lookup Or Initial it yourself
  57. *     2> use this ConnectionFactory to start a jms connection
  58. *        [spec to jms 1.1 api to get the main idea of it ]
  59. *     3> use connection to create a jms session
  60. *     4> get a queue destination / messege agent
  61. *     5> retrive a consumer from session
  62. *     6> start the jms connection to retrivte the message
  63. *     7> get message from consumer
  64. *
  65. * @return textMessege
  66. * @throws NamingException
  67. * @throws JMSException
  68. */
  69. public  String retriveingProcessing()  throws  NamingException, JMSException{
  70. Context ctx = new  InitialContext();
  71. ConnectionFactory cf = (ConnectionFactory) ctx.lookup("java:JmsXA" );
  72. Connection conn = cf.createConnection();
  73. Session session = conn.createSession(false , Session.AUTO_ACKNOWLEDGE);
  74. Destination dest = (Queue) ctx.lookup("queue/A" );
  75. MessageConsumer msgconsumer = session.createConsumer(dest);
  76. //MessageListener ml = new JmsListenner();
  77. //msgconsumer.setMessageListener(ml);
  78. conn.start();
  79. TextMessage msg = (TextMessage) msgconsumer.receive();
  80. conn.close();
  81. System.out.println("messege is"  + msg.getText());
  82. return  msg.getText();
  83. }
  84. }

<point to="" point=""></point> <point to="" point=""></point>

注意retrive函数中comment的掉的两行,消息Listener的作用是实现异步通讯,但是它有一个约定,必须和发送者
保持物理上的分离,针对于jboss而言,就要求这个Listener必须跑在容器外面。这是一个很搞的问题,每天Jms的邮件列表里面都有无数的这样的 问题发过来。但是回复的人很少。我自己也从来不回复。 其实我也不清楚写这篇文章到底是出于什么目的,怕只是让这么一个简单的问题有一个回答而已。

把下面这个程序跑起来就可以异步接受消息了。

java 代码

 

  1. package  com.javaeye.jms.jboss;
  2. import  java.util.Properties;
  3. import  javax.jms.Connection;
  4. import  javax.jms.ConnectionFactory;
  5. import  javax.jms.Destination;
  6. import  javax.jms.JMSException;
  7. import  javax.jms.MessageConsumer;
  8. import  javax.jms.MessageListener;
  9. import  javax.jms.Session;
  10. import  javax.naming.Context;
  11. import  javax.naming.InitialContext;
  12. import  javax.naming.NamingException;
  13. import  com.javaeye.spring.services.jms.mdp.JmsListenner;
  14. public   class  JbossJmsAsync {
  15. /**
  16. * @param args
  17. * @throws NamingException
  18. * @throws JMSException
  19. */
  20. public   static   void  main(String[] args)  throws  NamingException, JMSException {
  21. Properties pops = new  Properties();
  22. pops.setProperty("jboss.bind.address" ,  "0.0.0.0" );
  23. pops.setProperty("java.naming.factory.initial" ,  "org.jnp.interfaces.NamingContextFactory" );
  24. pops.setProperty("java.naming.factory.url.pkgs" ,  "org.jboss.naming:org.jnp.interfaces" );
  25. pops.setProperty("java.naming.provider.url" ,  "localhost" );
  26. Context ctx = new  InitialContext(pops);
  27. ConnectionFactory cf = (ConnectionFactory) ctx.lookup("ConnectionFactory" );
  28. Connection conn = cf.createConnection();
  29. Session session = conn.createSession(false , Session.AUTO_ACKNOWLEDGE);
  30. Destination dest = (Destination) ctx.lookup("queue/A" );
  31. MessageConsumer msgConsumer = session.createConsumer(dest);
  32. MessageListener ml = new  JmsListenner();
  33. msgConsumer.setMessageListener(ml);
  34. conn.start();
  35. }
  36. }

javaeye的主题好像是spring,为了迎合领导,下面我把这套东西跑在spring里面。同时我发现spring对jms的包装真的简单,而且还提供了一个模版,虽然这个模版的接口是在是很罗唆。

ps:今天是第1次用spring在reference里找了半天找不到方法注入的办法,于是google了一个注入办法,不合理的地方请大家指出。首先我通过方法来注入ConnectionFactory和Destination这两个对象来支撑jms环境

java 代码

 

  1. package  com.javaeye.spring.services.jms.mdp;
  2. import  java.util.Properties;
  3. import  javax.jms.ConnectionFactory;
  4. import  javax.jms.Destination;
  5. import  javax.jms.Queue;
  6. import  javax.naming.Context;
  7. import  javax.naming.InitialContext;
  8. import  javax.naming.NamingException;
  9. public   class  UserJmsTransactionUtil {
  10. private  String connectionFactoryJndiLookUp;
  11. private  String destinationJndiLookUp;
  12. private  String localConnectionFactoryJndiLookUp;
  13. private  String containerType;
  14. public  String getConnectionFactoryJndiLookUp() {
  15. return  connectionFactoryJndiLookUp;
  16. }
  17. public   void  setConnectionFactoryJndiLookUp(String connectionFactoryJndiLookUp) {
  18. this .connectionFactoryJndiLookUp = connectionFactoryJndiLookUp;
  19. }
  20. public  String getDestinationJndiLookUp() {
  21. return  destinationJndiLookUp;
  22. }
  23. public   void  setDestinationJndiLookUp(String destinationJndiLookUp) {
  24. this .destinationJndiLookUp = destinationJndiLookUp;
  25. }
  26. public  ConnectionFactory getConnectionFactory()  throws  NamingException{
  27. Context ctx = new  InitialContext();
  28. ConnectionFactory cf = (ConnectionFactory) ctx.lookup(connectionFactoryJndiLookUp);
  29. return  cf;
  30. }
  31. public  Destination getJmsDestination()  throws  NamingException{
  32. Context ctx = new  InitialContext();
  33. Destination dest = (Queue) ctx.lookup(destinationJndiLookUp);
  34. return  dest;
  35. }
  36. public  ConnectionFactory getQueueConnectionFactory()  throws  NamingException{
  37. Properties pops = new  Properties();
  38. pops.setProperty("jboss.bind.address" ,  "0.0.0.0" );
  39. pops.setProperty("java.naming.factory.initial" ,  "org.jnp.interfaces.NamingContextFactory" );
  40. pops.setProperty("java.naming.factory.url.pkgs" ,  "org.jboss.naming:org.jnp.interfaces" );
  41. pops.setProperty("java.naming.provider.url" ,  "localhost" );
  42. Context ctx = new  InitialContext(pops);
  43. ConnectionFactory cf = (ConnectionFactory) ctx.lookup(localConnectionFactoryJndiLookUp);
  44. return  cf;
  45. }
  46. public  Destination getLocalJmsDestination()  throws  NamingException{
  47. Properties pops = new  Properties();
  48. pops.setProperty("jboss.bind.address" ,  "0.0.0.0" );
  49. pops.setProperty("java.naming.factory.initial" ,  "org.jnp.interfaces.NamingContextFactory" );
  50. pops.setProperty("java.naming.factory.url.pkgs" ,  "org.jboss.naming:org.jnp.interfaces" );
  51. pops.setProperty("java.naming.provider.url" ,  "localhost" );
  52. Context ctx = new  InitialContext(pops);
  53. Destination dest = (Destination) ctx.lookup(destinationJndiLookUp);
  54. return  dest;
  55. }
  56. public  String getLocalConnectionFactoryJndiLookUp() {
  57. return  localConnectionFactoryJndiLookUp;
  58. }
  59. public   void  setLocalConnectionFactoryJndiLookUp(
  60. String localConnectionFactoryJndiLookUp) {
  61. this .localConnectionFactoryJndiLookUp = localConnectionFactoryJndiLookUp;
  62. }
  63. }

发送端的配置如下

xml 代码

 

  1. < beans >
  2. < bean   id = "userJmsUtil"   class = "com.javaeye.spring.services.jms.mdp.UserJmsTransactionUtil" >
  3. < property   name = "connectionFactoryJndiLookUp"   value = "java:JmsXA" > <!-- -->property >
  4. < property   name = "destinationJndiLookUp"   value = "queue/A" > <!-- -->property >
  5. < property   name = "localConnectionFactoryJndiLookUp"   value = "ConnectionFactory" > <!-- -->property >
  6. <!-- -->bean >
  7. < bean   id = "connectionFactory"   class = "org.springframework.beans.factory.config.MethodInvokingFactoryBean" >
  8. < property   name = "targetObject"   ref = "userJmsUtil" > <!-- -->property >
  9. < property   name = "targetMethod"   value = "getConnectionFactory" > <!-- -->property >
  10. <!-- -->bean >
  11. < bean   id = "queue"   class = "org.springframework.beans.factory.config.MethodInvokingFactoryBean" >
  12. < property   name = "targetObject"   ref = "userJmsUtil" > <!-- -->property >
  13. < property   name = "targetMethod"   value = "getJmsDestination" > <!-- -->property >
  14. <!-- -->bean >
  15. < bean   id = "jmsQueue"   class = "org.springframework.jms.core.JmsTemplate" >
  16. < property   name = "connectionFactory"   ref = "connectionFactory" > <!-- -->property >
  17. < property   name = "defaultDestination"   ref = "queue" > <!-- -->property >
  18. < property   name = "messageConverter" >
  19. < bean   class = "org.springframework.jms.support.converter.SimpleMessageConverter" > <!-- -->bean >
  20. <!-- -->property >
  21. <!-- -->bean >
  22. <!-- -->beans >

ps:javaeye的模版工具bug还真多,不管了.

如果使用Listenner的化,一样需要遵守发送者和接收者物理隔离的原则,我的做法是把发送者配到一个xml中,在把接受者配到另外一个xml中去,发送的配置绑定到容器里,接收者的跑在本地.否则spring初始化是过不去的.

下面这个程序是发送消息的程序.使用了spring的模版,发条消息比new个对象还简单.同时spring还提供了适配器的接口,一样通过声明式的配 置,这样可以在同一个接口里发送各种类型的消息了.同时支持事务,我还不知道这个有什么用呵呵,第1次使用嘛!但是就使用上来说,spring是最简单 的.2者都只需要注入一个对象而已.

java 代码

 

  1. @Test   public   void  send(){
  2. ApplicationContext ac = new  FileSystemXmlApplicationContext( "jms.xml" );
  3. BeanFactory bf = ac;
  4. JmsTemplate jt = (JmsTemplate) bf.getBean("jmsQueue" );
  5. jt.convertAndSend("2132134" );
  6. }

接收端的配置如下

xml 代码

 

  1. xml   version = "1.0"   encoding = "UTF-8" ?>
  2. >
  3. < beans >
  4. < bean   id = "listenner"   class = "com.javaeye.spring.services.jms.mdp.JmsListenner" > <!-- -->bean >
  5. < bean   id = "userJmsUtil"   class = "com.javaeye.spring.services.jms.mdp.UserJmsTransactionUtil" >
  6. < property   name = "connectionFactoryJndiLookUp"   value = "java:JmsXA" > <!-- -->property >
  7. < property   name = "destinationJndiLookUp"   value = "queue/A" > <!-- -->property >
  8. < property   name = "localConnectionFactoryJndiLookUp"   value = "ConnectionFactory" > <!-- -->property >
  9. <!-- -->bean >
  10. < bean   id = "localConnectionFactory"   class = "org.springframework.beans.factory.config.MethodInvokingFactoryBean" >
  11. < property   name = "targetObject"   ref = "userJmsUtil" > <!-- -->property >
  12. < property   name = "targetMethod"   value = "getQueueConnectionFactory" > <!-- -->property >
  13. <!-- -->bean >
  14. < bean   id = "localDestination"   class = "org.springframework.beans.factory.config.MethodInvokingFactoryBean" >
  15. < property   name = "targetObject"   ref = "userJmsUtil" > <!-- -->property >
  16. < property   name = "targetMethod"   value = "getLocalJmsDestination" > <!-- -->property >
  17. <!-- -->bean >
  18. < bean   id = "listenerContainer"   class = "org.springframework.jms.listener.DefaultMessageListenerContainer" >
  19. < property   name = "concurrentConsumers"   value = "5" > <!-- -->property >
  20. < property   name = "connectionFactory"   ref = "localConnectionFactory" > <!-- -->property >
  21. < property   name = "destination"   ref = "localDestination" > <!-- -->property >
  22. < property   name = "messageListener"   ref = "listenner" > <!-- -->property >
  23. <!-- -->bean >
  24. <!-- -->beans >

接收端由于需要从jbossmq里取ConnectionFactory和Destination,所以,我调用的是userJmsUtil的localLookup.这个函数的作用等同于发送者的那个函数,只不过前者是容器外获取,而后者是容器内的而已.

java 代码

 

  1. package  com.javaeye.spring.services.jms.mdp;
  2. import  javax.jms.JMSException;
  3. import  javax.jms.Message;
  4. import  javax.jms.MessageListener;
  5. import  javax.jms.TextMessage;
  6. public   class  JmsListenner  implements  MessageListener {
  7. public   void  onMessage(Message message) {
  8. try  {
  9. TextMessage msg = (TextMessage) message;
  10. System.out.println(msg.getText());
  11. } catch  (JMSException e) { e.printStackTrace(); }
  12. }
  13. }

spring对jms的整合里提到了一个jms provider ActiveMQ,要用一个开源框架要做的第一件事就是先跑一个demo起来,同样,我们要做的事还是获取ConnectionFactory和 Destination对象,还好,ActiveMQ的JNDI实现比jbossMQ还要简单,直接通过一个本地的Context就可以查到了,具体的可 以参照ActiveMQ官方的支持文档.

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。