JMS消息的发送和接收

[b]1.JMS消息的发送[/b]
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.QueueConnection;
import javax.jms.Session;

import com.sun.messaging.ConnectionConfiguration;
import com.sun.messaging.ConnectionFactory;
import com.sun.messaging.Queue;
/**
* JMS发送工具类
* @author owner
*
*/
public class JMSUtil {
/**
* 发送Queue消息
*
* @param content
* 消息传递内容
* @param queueName
* 消息对象传送序列名称.如:MQtest
*
*/
public static void send(Object content,String queueName) {
try {
ConnectionFactory connectionFactory = null;
QueueConnection connection = null;
Session session = null;
MessageProducer producer = null;
Message message = null;
try {
/** 建立消息服务器连接 */
connectionFactory = new ConnectionFactory();
/**服务器地址*/
String jmsServer = "localhost:8080";
/**用户名称*/
String jmsUser = "admin";
/**密码*/
String jmsPassword ="admin";

connectionFactory.setProperty("imqAddressList", jmsServer);
connectionFactory.setProperty(ConnectionConfiguration.imqDefaultUsername, jmsUser);
connectionFactory.setProperty(ConnectionConfiguration.imqDefaultPassword,jmsPassword);
/**创建queue点对点模式连接。topic是发布模式*/
connection = connectionFactory.createQueueConnection();
/**通过服务连接创建会话*/
session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);//AUTO_ACKNOWLEDGE自动提示
Destination destination = null;
try {
/**通过序列名称创建会话目标对象*/
destination = new Queue(queueName);
} catch (Throwable throwable) {
return;
}
/**创建消息制造者:用消息制造者来发送消息*/
producer = session.createProducer(destination);
/**开始连接消息服务器*/
connection.start();
// 字符串类型内容
if (content instanceof String) {
/**如果消息传递内容为字符串则通过会话创建文本消息*/
message = session.createTextMessage(content.toString());
}
// hash表型内容
else if (content instanceof HashMap) {
/**如果消息传递内容为HashMap则通过会话创建Map消息*/
HashMap contentMap = (HashMap) content;
MapMessage mm = session.createMapMessage();
/**把要发送的map内容转入会话创建的消息Map中*/
Iterator it = contentMap.keySet().iterator();
boolean isDifficulty = false;//判断是Map中值是否是对象:true为对象
while (it.hasNext()) {
String name = it.next().toString();
Object o = contentMap.get(name);
/**该会话创建的map消息中只存储值为String的字符串,如果是对象,则会创建值为object的对象消息*/
if (o != null && !(o instanceof String)) {
isDifficulty = true;
break;
}
if (o == null) {
mm.setString(name, "");
} else {
mm.setString(name, o.toString());
}
}
if (isDifficulty) {
/**如果是Map中存的值为非字符串则创建Object消息*/
message = session.createObjectMessage((Serializable) content);
} else {
message = mm;
}
}
// 其它类型内容
else {
/**如果消息内容不是map也不是字符串则直接创建一个Object类型消息*/
message = session
.createObjectMessage((Serializable) content);
}
/**消息制造者发送消息*/
producer.send(message);

}
// JMS链接例外,记录例外日志,并抛出错误信息
catch (JMSException ex) {
ex.printStackTrace();
} finally {
try {
/**关闭连接*/
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
} catch (Throwable ex1) {
ex1.printStackTrace();
}
}


}

[b]2.JMS消息的接收[/b]

第一步:创建mq连接工厂的实现。用于设置工厂构建连接地址
package com.test.jms;
import javax.jms.Connection;
import javax.jms.JMSException;

import com.sun.messaging.ConnectionConfiguration;
import com.sun.messaging.ConnectionFactory;

public class OpenMqConnectionFactory implements javax.jms.ConnectionFactory{

private ConnectionFactory connectionFactory;

public OpenMqConnectionFactory(String brokerAddress) throws JMSException {
connectionFactory = new ConnectionFactory();
connectionFactory.setProperty(ConnectionConfiguration.imqAddressList, brokerAddress);
}

public Connection createConnection() throws JMSException {
return connectionFactory.createConnection();
}

public Connection createConnection(String userName, String password) throws JMSException {
return connectionFactory.createConnection(userName, password);
}

}

第二步:创建JMS接收类

package com.test.jms;
import org.springframework.core.task.TaskExecutor;
public class JMSReciever {
private TaskExecutor taskExecutor;
public JMSReciever(TaskExecutor taskExecutor){
this.taskExecutor = taskExecutor;
}
private class MessagePrinterTask implements Runnable{
private String message;
public MessagePrinterTask(String message){
this.message = message;
}
public void run() {
System.err.println(">>>>>>>>>>>>>>>>>>新线程中:"+message);
}

}
/**
* 接收消息
* @param msg:消息内容(spring监听到消息后执行此方法,并将消息内容付给msg参数中)
*/
public void receiveMSG(Object msg){
//这个方法可以写具体操作
System.err.println(">>>>>>>>>>>>>>>>>接收消息后:"+msg.toString());
taskExecutor.execute(new MessagePrinterTask("新线程参数"));
//此对象为消息中包含对象。例如:msg是map。Map msp = (Map)msg;
Object msgContent =msg;

}

}
第三步:编写spring配置文件,定时获取消息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms-2.5.xsd"
default-lazy-init="true">
<jms:listener-container connection-factory="jmsFactory" task-executor="taskExecutor" concurrency="10" acknowledge="transacted">
<!--监听到序列号为MSG的消息时,通过会执行messageReceiver类中的receiveMSG方法
注意:MQtest与消息发送JMSUtil的参数queueName对应,即:接收指定队列中的消息。
-->
<jms:listener destination="MQtest" ref="messageReceiver" method="receiveMSG" /> <!--method监听到消息后要调用的方法-->
</jms:listener-container>
<!--mq连接工厂的实现。用于设置工厂构建连接地址-->
<bean id="jmsFactory" class="com.test.jms.OpenMqConnectionFactory">
<!--注入服务器地址-->
<constructor-arg type="java.lang.String" value="localhost:8080" />
</bean>
<!--监听到消息后要调用的类-->
<bean id="messageReceiver" class="com.test.jms.JMSReciever">
<constructor-arg ref="taskExecutor" />
</bean>
<!--spring的api,此类可以用execute(Runnable)来执行一个新线程。此类跟jms没关系只是自定义的类中注入一个”线程池任务执行者“,来执行其他自定义线程-->
<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="queueCapacity" value="5" />
</bean>

</beans>



依赖主要jar文件:
javaee.jar
imqjmsra.jar
什么是消息 消息是一个用于在组件和应用程序之间通讯的的方法。消息之间的传递是点对点的。任何终端之间都可以相互接受和发送消息。并且每个终端都必须遵守如下的规则 -> 创建消息 -> 发送消息 -> 接收消息 -> 读取消息 为什么要使用消息 理由很简单,消息是一个分布式的低耦合通讯方案。A发送一个消息到一个agent ,B作为接受者去agent上获取消息。但是A,B不需要同时到agent上去注册。agent作为一个中转为A,B提供搞效率的通讯服务。 Java消息服务支持两种消息模型:Point-to-Point消息(P2P)和发布订阅消息(Publish Subscribe messaging,简称Pub/Sub)。JMS规范并不要求供应商同时支持这两种消息模型,但开发者应该熟悉这两种消息模型的优势与缺点。 企业消息产品(或者有时称为面向消息的中间件产品)正逐渐成为公司内操作集成的关 键组件。这些产品可以将分离的业务组件组合成一个可靠灵活的系统。 除了传统的 MOM 供应商,企业消息产品也可以由数据库供应商和许多与网络相关的公 司来提供。 Java 语言的客户端和 Java 语言的中间层服务必须能够使用这些消息系统。JMS 为 Java 语言程序提供了一个通用的方式来获取这些系统。 JMS 是一个接口和相关语义的集合,那些语义定义了 JMS 客户端如何获取企业消息产品 的功能。 由于消息是点对点的,所以 JMS 的所有用户都称为客户端(clients)。JMS 应用由定义 消息的应用和一系列与他们交互的客户端组成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值