1.JMS介绍
JMS源于企业应用对于消息中间件的需求,使应用程序可以通过消息进行异步处理而互不影响。Sun公司和它的合作伙伴设计的JMS API定义了一组公共的应用程序接口和相应语法,使得Java程序能够和其他消息组件进行通信。JMS有四个组成部分:JMS服务提供者、消息管理对象、消息的生产者消费者和消息本身。
1)JMS服务提供者实现消息队列和通知,同时实现消息管理的API。JMS已经是J2EE API的一部分,J2EE服务器都提供JMS服务。
2) 消息管理对象提供对消息进行操作的API。JMS API中有两个消息管理对象:创建jms连接使用的工厂(ConnectionFactory)和目的地(Destination),根据消息的消费方式的不同ConnectionFactory可以分为QueueConnectionFactory和TopicConnectionFactory,目的地(Destination)可以分为队列(Queue)和主题(Topic)两种。
3)消息的生产者和消费者。消息的产生由JMS的客户端完成,JMS服务提供者负责管理这些消息,消息的消费者可以接收消息。消息的生产者可以分为――点对点消息发布者(P2P)和主题消息发布者(TopicPublisher)。所以,消息的消费者分为两类:主题消息的订阅者(TopicSubscriber)和点对点消息的接收者(queue receiver)
4)消息。消息是服务提供者和客户端之间传递信息所使用的信息单元。JMS消息由以下三部分组成:
消息头(header)――JMS消息头包含了许多字段,它们是消息发送后由JMS提供者或消息发送者产生,用来表示消息、设置优先权和失效时间等等,并且为消息确定路由。
属性(property)――用来添加删除消息头以外的附加信息。
消息体(body)――JMS中定义了5种消息体:ByteMessage、MapMessage、ObjectMessage、StreamMessage和TextMessage。
2.Messages 通信方式
上面提到JMS通信方式分为点对点通信和发布/订阅方式
1)点对点方式(point-to-point)
点对点的消息发送方式主要建立在 Message Queue,Sender,reciever上,Message Queue 存贮消息,Sneder 发送消息,receive接收消息.具体点就是Sender Client发送Message Queue ,而 receiver Cliernt从Queue中接收消息和"发送消息已接受"到Quere,确认消息接收。消息发送客户端与接收客户端没有时间上的依赖,发送客户端可以在任何时刻发送信息到Queue,而不需要知道接收客户端是不是在运行
2)发布/订阅 方式(publish/subscriber Messaging)
发布/订阅方式用于多接收客户端的方式.作为发布订阅的方式,可能存在多个接收客户端,并且接收端客户端与发送客户端存在时间上的依赖。一个接收端只能接收他创建以后发送客户端发送的信息。作为subscriber ,在接收消息时有两种方法,destination的receive方法,和实现message listener 接口的onMessage 方法。
为了能使例子跑起来,需要先配置一个jms服务器,参考ActiveMQ里面的配置文件结合tomcat进行了如下配置:
1.先在web.xml里面配置ActiveMQ需要的东西
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="2.4"
3 xmlns="http://java.sun.com/xml/ns/j2ee"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
6 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
7
8 <display-name>ActiveMQ Message Broker Web Application</display-name>
9
10 <description>
11 ActiveMQ web application to deploy the Broker in a servlet engine.
12 </description>
13
14 <context-param>
15 <param-name>brokerURI</param-name>
16 <param-value>/WEB-INF/activemq.xml</param-value>
17 </context-param>
18
19 <listener>
20 <listener-class>org.apache.activemq.web.SpringBrokerContextListener</listener-class>
21 </listener>
22
23 <welcome-file-list>
24 <welcome-file>index.jsp</welcome-file>
25 </welcome-file-list>
26 </web-app>
2.需要一个activemq.xml配置文件,里面的配置我还不懂,也是从下载ActiveMQ软件包里的例子里取出的
27 <!--
28 Licensed to the Apache Software Foundation (ASF) under one or more
29 contributor license agreements. See the NOTICE file distributed with
30 this work for additional information regarding copyright ownership.
31 The ASF licenses this file to You under the Apache License, Version 2.0
32 (the "License"); you may not use this file except in compliance with
33 the License. You may obtain a copy of the License at
34
35 http://www.apache.org/licenses/LICENSE-2.0
36
37 Unless required by applicable law or agreed to in writing, software
38 distributed under the License is distributed on an "AS IS" BASIS,
39 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
40 See the License for the specific language governing permissions and
41 limitations under the License.
42 -->
43 <!-- START SNIPPET: xbean -->
44 <beans
45 xmlns="http://www.springframework.org/schema/beans"
46 xmlns:amq="http://activemq.apache.org/schema/core"
47 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
48 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
49 http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
50 http://activemq.apache.org/camel/schema/spring http://activemq.apache.org/camel/schema/spring/camel-spring.xsd">
51
52
53 <broker xmlns="http://activemq.apache.org/schema/core" useJmx="false">
54
55 <persistenceAdapter>
56 <journaledJDBC journalLogFiles="5" dataDirectory="../data"/>
57 </persistenceAdapter>
58
59 <transportConnectors>
60 <transportConnector uri="tcp://localhost:61616"/>
61 <transportConnector uri="stomp://localhost:61613"/>
62 </transportConnectors>
63
64 </broker>
65
66 </beans>
67 <!-- END SNIPPET: xbean -->
3.定义消息体,这里可以是一个java对象,也可以是一个字符串,还可以是其它两种类型
对象必须序列化
68 package com.canofy.model;
69
70 import java.io.Serializable;
71
72 public class HelloWorld implements Serializable {
73 /**
74 *
75 */
76 private static final long serialVersionUID = -165720068500837198L;
77 private String title;
78 private String content;
79 public String getTitle() {
80 return title;
81 }
82 public void setTitle(String title) {
83 this.title = title;
84 }
85 public String getContent() {
86 return content;
87 }
88 public void setContent(String content) {
89 this.content = content;
90 }
91 }
4.发送消息类
92 package com.canofy.receive;
93
94
95 import javax.jms.Connection;
96 import javax.jms.Destination;
97 import javax.jms.JMSException;
98 import javax.jms.Message;
99 import javax.jms.MessageConsumer;
100 import javax.jms.ObjectMessage;
101 import javax.jms.Session;
102 import javax.jms.TextMessage;
103 import org.apache.activemq.ActiveMQConnectionFactory;
104
105 import com.canofy.model.HelloWorld;
106
107 public class ReceiveMessage {
108 private static final String url = "tcp://localhost:61616";
109 private static final String QUEUE_NAME = "choice.queue";
110
111 /**
112 * 接受消息
113 */
114 public void receiveMessage() {
115 Connection connection = null;
116 try {
117 //创建连接使用的工厂类JMS ConnectionFactory
118 ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
119 //使用管理对象JMS ConnectionFactory建立连接Connection
120 connection = connectionFactory.createConnection();
121 connection.start();
122 //使用连接Connection 建立会话Session
123 Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
124 //使用会话Session和管理对象Destination创建消息消费者MessageReceiver
125 Destination destination = session.createQueue(QUEUE_NAME);
126 MessageConsumer consumer = session.createConsumer(destination);
127 //使用消息消费者MessageReceiver接受消息,需要用setMessageListener将MessageListener接口绑定到MessageReceiver
128 //消息消费者必须实现了MessageListener接口,需要定义onMessage事件方法。
129 consumeMessagesAndClose(connection, session, consumer);
130 } catch (Exception e) {
131 System.out.println(e.toString());
132 }
133 }
134
135 protected void consumeMessagesAndClose(Connection connection,Session session, MessageConsumer consumer) throws JMSException {
136 for (int i = 0; i < 1;) {
137 Message message = consumer.receive(1000);
138 if (message != null) {
139 i++;
140 onMessage(message);
141 }
142 }
143 System.out.println("Closing connection");
144 consumer.close();
145 session.close();
146 connection.close();
147 }
148
149 public void onMessage(Message message) {
150 try {
151 // if (message instanceof TextMessage) {
152 // TextMessage txtMsg = (TextMessage) message;
153 // String msg = txtMsg.getText();
154 // System.out.println("Received: " + msg);
155 // }
156 //判断message的类型,然后转为需要的message类型,最后取出需要的数据
157 if (message instanceof ObjectMessage) {
158 ObjectMessage txtMsg = (ObjectMessage) message;
159 HelloWorld hw=(HelloWorld)txtMsg.getObject();
160 // HelloWorld msg =(HelloWorld) txtMsg.getJMSType();
161 System.out.println("Received: " +hw.getTitle()+"/n"+"/t"+hw.getContent());
162 }
163 } catch (Exception e) {
164 e.printStackTrace();
165 }
166
167 }
168
169 public static void main(String args[]) {
170 ReceiveMessage rm = new ReceiveMessage();
171 rm.receiveMessage();
172 }
173
174 }
5.接收消息类
175 package com.canofy.send;
176
177 import javax.jms.Connection;
178 import javax.jms.Destination;
179 import javax.jms.JMSException;
180 import javax.jms.MessageProducer;
181 import javax.jms.ObjectMessage;
182 import javax.jms.Session;
183 import javax.jms.TextMessage;
184 import org.apache.activemq.ActiveMQConnectionFactory;
185
186 import com.canofy.model.HelloWorld;
187
188 public class SendMessage {
189 private static final String url ="tcp://localhost:61616";
190 private static final String QUEUE_NAME ="choice.queue";
191 protected String expectedBody = "<hello>world!</hello>";
192 /**
193 * 发送信息
194 * @throws JMSException
195 */
196 public void sendMessage() throws JMSException{
197 HelloWorld hw=new HelloWorld();
198 hw.setTitle("test");
199 hw.setContent("content");
200 Connection connection =null;
201 try{
202 //创建连接使用的工厂类JMS ConnectionFactory
203 ActiveMQConnectionFactory connectionFactory =new ActiveMQConnectionFactory(url);
204 //使用管理对象JMS ConnectionFactory建立连接Connection
205 connection = (Connection)connectionFactory.createConnection();
206 connection.start();
207 //使用连接Connection 建立会话Session
208 Session session = (Session)connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
209 Destination destination = session.createQueue(QUEUE_NAME);
210 //使用会话Session和管理对象Destination创建消息生产者MessageSender
211 MessageProducer producer = session.createProducer(destination);
212 //TextMessage message = session.createTextMessage(expectedBody);
213 //message.setStringProperty("headname", "remoteB");
214 //producer.send(message);
215 ObjectMessage om=session.createObjectMessage();
216 om.setObject(hw);
217 //om.setStringProperty("headname", "remoteB");
218 //使用消息生产者MessageSender发送消息
219 producer.send(om);
220 }catch(Exception e){
221 e.printStackTrace();
222 }
223 }
224
225 public static void main(String[] args){
226 SendMessage sndMsg = new SendMessage();
227 try{
228 sndMsg.sendMessage();
229 }catch(Exception ex){
230 System.out.println(ex.toString());
231 }
232 }
233 }