---
title: "Jms基础知识整理"
author: "houzi"
date: "2009-05-19T16:36:15Z"
tags: []
slug: "jms"
draft: false
lastmod: "2009-05-19T16:36:15Z"
id: 391278
url: "https://code-chris.iteye.com/blog/391278"
---

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

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

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

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

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

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

java 代码

 

01. package  com.javaeye.jms.jboss;
02. import  javax.jms.Connection;
03. import  javax.jms.ConnectionFactory;
04. import  javax.jms.Destination;
05. import  javax.jms.JMSException;
06. import  javax.jms.MessageConsumer;
07. import  javax.jms.MessageProducer;
08. import  javax.jms.Queue;
09. 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&gt; get an ConnectionFactory use JNDI Lookup Or Initial it yourself
23. *     2&gt; use this ConnectionFactory to start a jms connection
24. *        \[spec to jms 1.1 api to get the main idea of it ]
25. *     3&gt; use connection to create a jms session
26. *     4&gt; get a queue destination / messege agent
27. *     5&gt; start the Producer\[jms1.1 spec] by a session
28. *     6&gt; get messege Object or initial it yourself by implements the messegeor
29. *        it's sub interfaces
30. *     7&gt; call sender or send it selfing
31. *     8&gt; 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&gt; get an ConnectionFactory use JNDI Lookup Or Initial it yourself
57. *     2&gt; use this ConnectionFactory to start a jms connection
58. *        \[spec to jms 1.1 api to get the main idea of it ]
59. *     3&gt; use connection to create a jms session
60. *     4&gt; get a queue destination / messege agent
61. *     5&gt; retrive a consumer from session
62. *     6&gt; start the jms connection to retrivte the message
63. *     7&gt; 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. }

&lt;point to="" point=""&gt;&lt;/point&gt; &lt;point to="" point=""&gt;&lt;/point&gt;

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

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

java 代码

 

01. package  com.javaeye.jms.jboss;
02. import  java.util.Properties;
03. import  javax.jms.Connection;
04. import  javax.jms.ConnectionFactory;
05. import  javax.jms.Destination;
06. import  javax.jms.JMSException;
07. import  javax.jms.MessageConsumer;
08. import  javax.jms.MessageListener;
09. 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 代码

 

01. package  com.javaeye.spring.services.jms.mdp;
02. import  java.util.Properties;
03. import  javax.jms.ConnectionFactory;
04. import  javax.jms.Destination;
05. import  javax.jms.Queue;
06. import  javax.naming.Context;
07. import  javax.naming.InitialContext;
08. import  javax.naming.NamingException;
09. 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 代码

 

01. &lt; beans &gt;
02. &lt; bean   id = "userJmsUtil"   class = "com.javaeye.spring.services.jms.mdp.UserJmsTransactionUtil" &gt;
03. &lt; property   name = "connectionFactoryJndiLookUp"   value = "java:JmsXA" &gt; &lt;!-- --&gt;property &gt;
04. &lt; property   name = "destinationJndiLookUp"   value = "queue/A" &gt; &lt;!-- --&gt;property &gt;
05. &lt; property   name = "localConnectionFactoryJndiLookUp"   value = "ConnectionFactory" &gt; &lt;!-- --&gt;property &gt;
06. &lt;!-- --&gt;bean &gt;
07. &lt; bean   id = "connectionFactory"   class = "org.springframework.beans.factory.config.MethodInvokingFactoryBean" &gt;
08. &lt; property   name = "targetObject"   ref = "userJmsUtil" &gt; &lt;!-- --&gt;property &gt;
09. &lt; property   name = "targetMethod"   value = "getConnectionFactory" &gt; &lt;!-- --&gt;property &gt;
10. &lt;!-- --&gt;bean &gt;
11. &lt; bean   id = "queue"   class = "org.springframework.beans.factory.config.MethodInvokingFactoryBean" &gt;
12. &lt; property   name = "targetObject"   ref = "userJmsUtil" &gt; &lt;!-- --&gt;property &gt;
13. &lt; property   name = "targetMethod"   value = "getJmsDestination" &gt; &lt;!-- --&gt;property &gt;
14. &lt;!-- --&gt;bean &gt;
15. &lt; bean   id = "jmsQueue"   class = "org.springframework.jms.core.JmsTemplate" &gt;
16. &lt; property   name = "connectionFactory"   ref = "connectionFactory" &gt; &lt;!-- --&gt;property &gt;
17. &lt; property   name = "defaultDestination"   ref = "queue" &gt; &lt;!-- --&gt;property &gt;
18. &lt; property   name = "messageConverter" &gt;
19. &lt; bean   class = "org.springframework.jms.support.converter.SimpleMessageConverter" &gt; &lt;!-- --&gt;bean &gt;
20. &lt;!-- --&gt;property &gt;
21. &lt;!-- --&gt;bean &gt;
22. &lt;!-- --&gt;beans &gt;

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 代码

 

01. xml   version = "1.0"   encoding = "UTF-8" ?&gt;
02. &gt;
03. &lt; beans &gt;
04. &lt; bean   id = "listenner"   class = "com.javaeye.spring.services.jms.mdp.JmsListenner" &gt; &lt;!-- --&gt;bean &gt;
05. &lt; bean   id = "userJmsUtil"   class = "com.javaeye.spring.services.jms.mdp.UserJmsTransactionUtil" &gt;
06. &lt; property   name = "connectionFactoryJndiLookUp"   value = "java:JmsXA" &gt; &lt;!-- --&gt;property &gt;
07. &lt; property   name = "destinationJndiLookUp"   value = "queue/A" &gt; &lt;!-- --&gt;property &gt;
08. &lt; property   name = "localConnectionFactoryJndiLookUp"   value = "ConnectionFactory" &gt; &lt;!-- --&gt;property &gt;
09. &lt;!-- --&gt;bean &gt;
10. &lt; bean   id = "localConnectionFactory"   class = "org.springframework.beans.factory.config.MethodInvokingFactoryBean" &gt;
11. &lt; property   name = "targetObject"   ref = "userJmsUtil" &gt; &lt;!-- --&gt;property &gt;
12. &lt; property   name = "targetMethod"   value = "getQueueConnectionFactory" &gt; &lt;!-- --&gt;property &gt;
13. &lt;!-- --&gt;bean &gt;
14. &lt; bean   id = "localDestination"   class = "org.springframework.beans.factory.config.MethodInvokingFactoryBean" &gt;
15. &lt; property   name = "targetObject"   ref = "userJmsUtil" &gt; &lt;!-- --&gt;property &gt;
16. &lt; property   name = "targetMethod"   value = "getLocalJmsDestination" &gt; &lt;!-- --&gt;property &gt;
17. &lt;!-- --&gt;bean &gt;
18. &lt; bean   id = "listenerContainer"   class = "org.springframework.jms.listener.DefaultMessageListenerContainer" &gt;
19. &lt; property   name = "concurrentConsumers"   value = "5" &gt; &lt;!-- --&gt;property &gt;
20. &lt; property   name = "connectionFactory"   ref = "localConnectionFactory" &gt; &lt;!-- --&gt;property &gt;
21. &lt; property   name = "destination"   ref = "localDestination" &gt; &lt;!-- --&gt;property &gt;
22. &lt; property   name = "messageListener"   ref = "listenner" &gt; &lt;!-- --&gt;property &gt;
23. &lt;!-- --&gt;bean &gt;
24. &lt;!-- --&gt;beans &gt;

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

java 代码

 

01. package  com.javaeye.spring.services.jms.mdp;
02. import  javax.jms.JMSException;
03. import  javax.jms.Message;
04. import  javax.jms.MessageListener;
05. import  javax.jms.TextMessage;
06. public   class  JmsListenner  implements  MessageListener {
07. public   void  onMessage(Message message) {
08. try  {
09. 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官方的支持文档.