2.2 新建web应用(webapps/jms-test),修改WEB-INF/web.xml文件:
增加一个自启动Servlet,该Servlet实现了MessageListener接口,作为Topic消息的Listener端。
<servlet>
<servlet-name>jms-listener</servlet-name>
<servlet-class>
com.flvcd.servlet.JMSListener
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
2.3 修改activemq.xml文件:
为了支持持久化消息,需修改ActiveMQ的配置文件如下,使用默认的AMQ Message Store方式(索引文件方式)存储消息,据官网介绍是快速、稳定的。数据库存储方式可参照官网相关文档。
<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" persistent="true" useShutdownHook="false">
<persistenceAdapter>
<amqPersistenceAdapter directory="activemq-data" maxFileLength="32mb"/>
</persistenceAdapter>
</broker>
3、Listener端(JMSListener.java)完整实现:
package com.flvcd.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;
public class JMSListener extends HttpServlet implements MessageListener{
/** 初始化jms连接,创建topic监听器 */
public void init(ServletConfig config) throws ServletException{
try {
InitialContext initCtx = new InitialContext();
Context envContext = (Context) initCtx.lookup("java:comp/env");
ConnectionFactory connectionFactory = (ConnectionFactory) envContext.lookup("jms/FailoverConnectionFactory");
Connection connection = connectionFactory.createConnection();
connection.setClientID("MyClient");
Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//普通消息订阅者,无法接收持久消息
//MessageConsumer consumer = jmsSession.createConsumer((Destination) envContext.lookup("jms/topic/MyTopic"));
//基于Topic创建持久的消息订阅者,前提:Connection必须指定一个唯一的clientId,当前为MyClient
TopicSubscriber consumer = jmsSession.createDurableSubscriber((Topic) envContext.lookup("jms/topic/MyTopic"), "MySub");
consumer.setMessageListener(this);
connection.start();
} catch (NamingException e) {
e.printStackTrace();
} catch (JMSException e) {
e.printStackTrace();
}
}
/** 接收消息,做对应处理 */
public void onMessage(Message message) {
if (checkText(message, "RefreshArticleId") != null) {
String articleId = checkText(message, "RefreshArticleId");
System.out.println("接收刷新文章消息,开始刷新文章ID=" + articleId);
}
else if (checkText(message, "RefreshThreadId") != null) {
String threadId = checkText(message, "RefreshThreadId");
System.out.println("接收刷新论坛帖子消息,开始刷新帖子ID=" + threadId);
} else {
System.out.println("接收普通消息,不做任何处理!");
}
}
private static String checkText(Message m, String s) {
try {
return m.getStringProperty(s);
} catch (JMSException e) {
e.printStackTrace(System.out);
return null;
}
}
}
编译JMSListener.java至classes目录:
javac -cp .;D:\apache-tomcat-6.0.14\lib\servlet-api.jar;D:\apache-tomcat-6.0.14\lib\geronimo-jms_1.1_spec-1.1.1.jar;D:\apache-tomcat-6.0.14\lib\activemq-core-5.1.0.jar -d . JMSListener.java
注:D:\apache-tomcat-6.0.14请替换成本地对应目录。