ActiveMQ实战2:ActiveMQ Tomcat

 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

你可能感兴趣的:(tomcat,activemq)