当前位置:首页 > 开发 > 互联网 > 正文

ActiveMQ实战2:ActiveMQ Tomcat

发表于: 2015-04-02   作者:_wy_   来源:转载   浏览:
摘要:  1.新建一个servlet并实现MessageListener接口 package com.activemq.webActivemq; import javax.jms.*; import javax.jms.Message; import javax.servlet.http.HttpServlet; import org.apache.activemq.*;

 1.新建一个servlet并实现MessageListener接口

package com.activemq.webActivemq;

import javax.jms.*;
import javax.jms.Message;
import javax.servlet.http.HttpServlet;

import org.apache.activemq.*;

public class JMSListener extends HttpServlet implements MessageListener {
	
    private static final long serialVersionUID = -8455543162505698971L;
    private String user = ActiveMQConnection.DEFAULT_USER;    
    private String password = ActiveMQConnection.DEFAULT_PASSWORD;    
    private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    //queue必须和消息生产者的队列名一致
    private String queue = "TOOL.DEFAULT";    
    private Destination destination = null;    
    private Connection connection = null;    
    private Session session = null;    
    private MessageConsumer consumer = null; 
    
    public JMSListener(){
        ActiveMQConnectionFactory connectionFactory = 
        		new ActiveMQConnectionFactory(user,password, url);
        try {
            connection = connectionFactory.createConnection();
            session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue(queue);
            consumer = session.createConsumer(destination);
            consumer.setMessageListener(this);
            connection.start();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
            
	public void onMessage(Message message) {
		try {
			TextMessage msg = (TextMessage) message;
			System.out.println("接收到的消息为:"+msg.getText());
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}

2.在web.xml文件增加如下代码

 <!-- 添加jms监听 -->
<servlet>
<servlet-name>jms-listener</servlet-name>
<servlet-class>
       com.activemq.webActivemq.JMSListener
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>

3.启动tomcat

注:以上只有消息消费者的代码,消息生产者代码参考

ActiveMQ实战1:ActiveMQ Java  http://425826501.iteye.com/blog/2198115

ActiveMQ实战2:ActiveMQ Tomcat

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

推荐文章
编辑推荐
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号