JMS初试

用途貌似是实现异步处理的机制,前台处理完一笔业务的时候,不用去等待后台的数据返回,等待后台处理完毕之后,再发送信息给前台提示(或者由前台来进行手动获取),即所谓的发布/订阅方式和点对点方式。

参考地址:http://www.iteye.com/topic/275045

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需要的东西

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>ActiveMQ Message Broker Web Application</display-name>

<description>
ActiveMQ web application to deploy the Broker in a servlet engine.
</description>

<context-param>
<param-name>brokerURI</param-name>
<param-value>/WEB-INF/activemq.xml</param-value>
</context-param>

<listener>
<listener-class>org.apache.activemq.web.SpringBrokerContextListener</listener-class>
</listener>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>



2.需要一个activemq.xml配置文件,里面的配置我还不懂,也是从下载ActiveMQ软件包里的例子里取出的

<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- START SNIPPET: xbean -->
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
http://activemq.apache.org/camel/schema/spring http://activemq.apache.org/camel/schema/spring/camel-spring.xsd">


<broker xmlns="http://activemq.apache.org/schema/core" useJmx="false">

<persistenceAdapter>
<journaledJDBC journalLogFiles="5" dataDirectory="../data"/>
</persistenceAdapter>

<transportConnectors>
<transportConnector uri="tcp://localhost:61616"/>
<transportConnector uri="stomp://localhost:61613"/>
</transportConnectors>

</broker>

</beans>
<!-- END SNIPPET: xbean -->


3.定义消息体,这里可以是一个java对象,也可以是一个字符串,还可以是其它两种类型
对象必须序列化


package com.canofy.model;

import java.io.Serializable;

public class HelloWorld implements Serializable {
/**
*
*/
private static final long serialVersionUID = -165720068500837198L;
private String title;
private String content;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}


4.发送消息类

package com.canofy.receive;


import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.canofy.model.HelloWorld;

public class ReceiveMessage {
private static final String url = "tcp://localhost:61616";
private static final String QUEUE_NAME = "choice.queue";

/**
* 接受消息
*/
public void receiveMessage() {
Connection connection = null;
try {
//创建连接使用的工厂类JMS ConnectionFactory
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
//使用管理对象JMS ConnectionFactory建立连接Connection
connection = connectionFactory.createConnection();
connection.start();
//使用连接Connection 建立会话Session
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//使用会话Session和管理对象Destination创建消息消费者MessageReceiver
Destination destination = session.createQueue(QUEUE_NAME);
MessageConsumer consumer = session.createConsumer(destination);
//使用消息消费者MessageReceiver接受消息,需要用setMessageListener将MessageListener接口绑定到MessageReceiver
//消息消费者必须实现了MessageListener接口,需要定义onMessage事件方法。
consumeMessagesAndClose(connection, session, consumer);
} catch (Exception e) {
System.out.println(e.toString());
}
}

protected void consumeMessagesAndClose(Connection connection,Session session, MessageConsumer consumer) throws JMSException {
for (int i = 0; i < 1;) {
Message message = consumer.receive(1000);
if (message != null) {
i++;
onMessage(message);
}
}
System.out.println("Closing connection");
consumer.close();
session.close();
connection.close();
}

public void onMessage(Message message) {
try {
// if (message instanceof TextMessage) {
// TextMessage txtMsg = (TextMessage) message;
// String msg = txtMsg.getText();
// System.out.println("Received: " + msg);
// }
//判断message的类型,然后转为需要的message类型,最后取出需要的数据
if (message instanceof ObjectMessage) {
ObjectMessage txtMsg = (ObjectMessage) message;
HelloWorld hw=(HelloWorld)txtMsg.getObject();
// HelloWorld msg =(HelloWorld) txtMsg.getJMSType();
System.out.println("Received: " +hw.getTitle()+"\n"+"\t"+hw.getContent());
}
} catch (Exception e) {
e.printStackTrace();
}

}

public static void main(String args[]) {
ReceiveMessage rm = new ReceiveMessage();
rm.receiveMessage();
}

}


5.接收消息类

package com.canofy.send;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.canofy.model.HelloWorld;

public class SendMessage {
private static final String url ="tcp://localhost:61616";
private static final String QUEUE_NAME ="choice.queue";
protected String expectedBody = "<hello>world!</hello>";
/**
* 发送信息
* @throws JMSException
*/
public void sendMessage() throws JMSException{
HelloWorld hw=new HelloWorld();
hw.setTitle("test");
hw.setContent("content");
Connection connection =null;
try{
//创建连接使用的工厂类JMS ConnectionFactory
ActiveMQConnectionFactory connectionFactory =new ActiveMQConnectionFactory(url);
//使用管理对象JMS ConnectionFactory建立连接Connection
connection = (Connection)connectionFactory.createConnection();
connection.start();
//使用连接Connection 建立会话Session
Session session = (Session)connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(QUEUE_NAME);
//使用会话Session和管理对象Destination创建消息生产者MessageSender
MessageProducer producer = session.createProducer(destination);
//TextMessage message = session.createTextMessage(expectedBody);
//message.setStringProperty("headname", "remoteB");
//producer.send(message);
ObjectMessage om=session.createObjectMessage();
om.setObject(hw);
//om.setStringProperty("headname", "remoteB");
//使用消息生产者MessageSender发送消息
producer.send(om);
}catch(Exception e){
e.printStackTrace();
}
}

public static void main(String[] args){
SendMessage sndMsg = new SendMessage();
try{
sndMsg.sendMessage();
}catch(Exception ex){
System.out.println(ex.toString());
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值