tomcat与JMS
一、修改配置文件
1.1修改Tomcat的conf/context.xml文件:
在<context></context>节点中添加以下内容:
<Resource
name="jms/FailoverConnectionFactory"
auth="Container"
type="org.apache.activemq.ActiveMQConnectionFactory"
description="JMSConnectionFactory"
factory="org.apache.activemq.jndi.JNDIReferenceFactory"
brokerURL="failover:(tcp://localhost:61616)?initialReconnectDelay=100&maxReconnectAttempts=5"
brokername="localhost"
useEmbeddedBroker="false"/>
<Resource
name="jms/NormalConnectionFactory"
auth="Container"
type="org.apache.activemq.ActiveMQConnectionFactory"
description="JMSConnectionFactory"
factory="org.apache.activemq.jndi.JNDIReferenceFactory"
brokerURL="tcp://localhost:61616"
brokername="localhost"
useEmbeddedBroker="false"/>
<Resourcename="jms/topic/MyTopic"
auth="Container"
type="org.apache.activemq.command.ActiveMQTopic"
factory="org.apache.activemq.jndi.JNDIReferenceFactory"
physicalname="MY.TEST.FOO"/>
<Resourcename="jms/queue/MyQueue"
auth="Container"
type="org.apache.activemq.command.ActiveMQQueue"
factory="org.apache.activemq.jndi.JNDIReferenceFactory"
physicalname="MY.TEST.FOO.QUEUE"/>
二、详细示例
2.1监听类
packagecom.flvcd.servlet;
importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
importjavax.naming.*;
importjavax.jms.*;
importorg.apache.activemq.ActiveMQConnectionFactory;
publicclassJMSListenerextendsHttpServletimplementsMessageListener{
/**初始化jms连接,创建topic监听器*/
publicvoidinit(ServletConfigconfig)throwsServletException{
try{
InitialContextinitCtx=newInitialContext();
ContextenvContext=(Context)initCtx.lookup("java:comp/env");
ConnectionFactoryconnectionFactory=(ConnectionFactory)envContext
.lookup("jms/FailoverConnectionFactory");
Connectionconnection=connectionFactory.createConnection();
connection.setClientID("MyClient");
SessionjmsSession=connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
//普通消息订阅者,无法接收持久消息//MessageConsumerconsumer=
//jmsSession.createConsumer((Destination)
//envContext.lookup("jms/topic/MyTopic"));
////基于Topic创建持久的消息订阅者,前提:Connection必须指定一个唯一的clientId,当前为MyClient
TopicSubscriberconsumer=jmsSession.createDurableSubscriber((Topic)envContext.lookup("jms/topic/MyTopic"),"MySub");
consumer.setMessageListener(this);
connection.start();
}catch(NamingExceptione){
e.printStackTrace();
}catch(JMSExceptione){
e.printStackTrace();
}
}
/**接收消息,做对应处理*/
publicvoidonMessage(Messagemessage){
if(checkText(message,"RefreshArticleId")!=null){
StringarticleId=checkText(message,"RefreshArticleId");
System.out.println("接收刷新文章消息,开始刷新文章id="+articleId);
}elseif(checkText(message,"RefreshThreadId")!=null){
StringthreadId=checkText(message,"RefreshThreadId");
System.out.println("接收刷新论坛帖子消息,开始刷新帖子id="+threadId);
}else{
System.out.println("接收普通消息,不做任何处理!");
}
}
privatestaticStringcheckText(Messagem,Strings){
try{
returnm.getStringProperty(s);
}catch(JMSExceptione){
e.printStackTrace(System.out);
returnnull;
}
}
}
2.2发布类
packagecom.flvcd.servlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.jms.Connection;
importjavax.jms.ConnectionFactory;
importjavax.jms.DeliveryMode;
importjavax.jms.Destination;
importjavax.jms.JMSException;
importjavax.jms.Message;
importjavax.jms.MessageListener;
importjavax.jms.MessageProducer;
importjavax.jms.Session;
importjavax.naming.Context;
importjavax.naming.InitialContext;
importjavax.naming.NamingException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
publicclassMyPublishextendsHttpServletimplementsMessageListener{
//定义初始化所需要的变量
privateInitialContextinitCtx;
privateContextenvContext;
privateConnectionFactoryconnectionFactory;
privateConnectionconnection;
privateSessionjmsSession;
privateMessageProducerproducer;
publicvoidonMessage(Messagemessage){
//TODOAuto-generatedmethodstub
}
/**
*Constructoroftheobject.
*/
publicMyPublish(){
super();
}
/**
*Destructionoftheservlet.<br>
*/
publicvoiddestroy(){
super.destroy();//Justputs"destroy"stringinlog
//Putyourcodehere
}
/**
*ThedoGetmethodoftheservlet.<br>
*
*Thismethodiscalledwhenaformhasitstagvaluemethodequalstoget.
*
*@paramrequesttherequestsendbytheclienttotheserver
*@paramresponsetheresponsesendbytheservertotheclient
*@throwsServletExceptionifanerroroccurred
*@throwsIOExceptionifanerroroccurred
*/
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doPost(request,response);
}
/**
*ThedoPostmethodoftheservlet.<br>
*
*Thismethodiscalledwhenaformhasitstagvaluemethodequalstopost.
*
*@paramrequesttherequestsendbytheclienttotheserver
*@paramresponsetheresponsesendbytheservertotheclient
*@throwsServletExceptionifanerroroccurred
*@throwsIOExceptionifanerroroccurred
*/
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
Stringcontent=request.getParameter("content");
//设置持久方式
try{
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
MessagetestMessage=jmsSession.createMessage();
//发布刷新文章消息
testMessage.setStringProperty("RefreshArticleId",content);
producer.send(testMessage);
//发布刷新帖子消息
testMessage.clearProperties();
testMessage.setStringProperty("RefreshThreadId",content);
producer.send(testMessage);
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*Initializationoftheservlet.<br>
*
*@throwsServletExceptionifanerroroccurs
*/
publicvoidinit()throwsServletException{
//Putyourcodehere
try{
initCtx=newInitialContext();
envContext=(Context)initCtx.lookup("java:comp/env");
connectionFactory=(ConnectionFactory)envContext.lookup("jms/NormalConnectionFactory");
connection=connectionFactory.createConnection();
jmsSession=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
producer=jmsSession.createProducer((Destination)envContext.lookup("jms/topic/MyTopic"));
}catch(NamingExceptione){
e.printStackTrace();
}catch(JMSExceptione){
e.printStackTrace();
}
}
}
2.3MyPublish.jsp
<formaction="myPublish.do">
<inputtype="text"name="content"/>
<inputtype="submit"value="提交">
/form>
2.4web.xml也需要相应配置,详细见附件。
关键代码:
<servlet>
<servlet-name>jms-listener</servlet-name>
<servlet-class>
com.flvcd.servlet.JMSListener
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
因上传限制附件中缺少ActiveMq.jar,请自行下载。