tomcat与JMS

原文地址:http://madfroghe.iteye.com/blog/927637
一、修改配置文件
1.1 修改Tomcat的conf/context.xml文件:
在<context></context>节点中添加以下内容:

<Resource
        name="jms/FailoverConnectionFactory"
        auth="Container"
        type="org.apache.activemq.ActiveMQConnectionFactory"
        description="JMS Connection Factory"
        factory="org.apache.activemq.jndi.JNDIReferenceFactory"
    brokerURL="failover:(tcp://localhost:61616)?initialReconnectDelay=100&amp;maxReconnectAttempts=5"
        brokerName="localhost"
        useEmbeddedBroker="false"/>
    <Resource
        name="jms/NormalConnectionFactory"
        auth="Container"
        type="org.apache.activemq.ActiveMQConnectionFactory"
        description="JMS Connection Factory"
        factory="org.apache.activemq.jndi.JNDIReferenceFactory"
        brokerURL="tcp://localhost:61616"
        brokerName="localhost"
        useEmbeddedBroker="false"/>
    <Resource name="jms/topic/MyTopic"
        auth="Container"
        type="org.apache.activemq.command.ActiveMQTopic"
        factory="org.apache.activemq.jndi.JNDIReferenceFactory"
        physicalName="MY.TEST.FOO"/>
    <Resource name="jms/queue/MyQueue"
        auth="Container"
        type="org.apache.activemq.command.ActiveMQQueue"
        factory="org.apache.activemq.jndi.JNDIReferenceFactory"
        physicalName="MY.TEST.FOO.QUEUE"/>
二、详细示例
2.1 监听类
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;
        }
    }
}
2.2 发布类
package com.flvcd.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyPublish extends HttpServlet implements MessageListener {
    
    
    //定义初始化所需要的变量
    private InitialContext initCtx;
    private Context envContext;
    private ConnectionFactory connectionFactory;
    private Connection connection;
    private Session jmsSession;
    private MessageProducer producer;
    
    
    public void onMessage(Message message) {
        // TODO Auto-generated method stub

    }

    /**
     * Constructor of the object.
     */
    public MyPublish() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String content=request.getParameter("content");
        //设置持久方式
        try {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            Message testMessage = jmsSession.createMessage();
            // 发布刷新文章消息
            testMessage.setStringProperty("RefreshArticleId", content);
            producer.send(testMessage);
            // 发布刷新帖子消息
            testMessage.clearProperties();
            testMessage.setStringProperty("RefreshThreadId", content);
            producer.send(testMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
        try {
            initCtx = new InitialContext();
            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 (NamingException e) {
            e.printStackTrace();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
2.3 MyPublish.jsp
<form action="myPublish.do">
    <input type="text" name="content" />
    <input type="submit" value="提交" >
/form>
2.4 web.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,请自行下载。

猜你喜欢

转载自you366.iteye.com/blog/1726146
jms