基于Tomcat容器的ActiveMQ简单实例

      在tomcat中配置ConnectionFactory和ActiveMQQueue,通过JNDI方式实现ActiveMQ。因为JNDI配置在  
      在tomcat中配置ConnectionFactory和ActiveMQQueue,通过JNDI方式实现ActiveMQ。因为JNDI配置在
tomcat容器中所以必须通过jsp访问tomcat容器。  
tomcat容器中所以必须通过jsp访问tomcat容器。

首先在在tomcat的lib目录添加如下jar文件。

<classpathentry kind="lib" path="src/activemq-all-5.5.0.jar"/>   

    <classpathentry kind="lib" path="src/slf4j-api-1.5.2-sources.jar"/>   


    <classpathentry kind="lib" path="src/slf4j-api-1.5.2.jar"/>   


    <classpathentry kind="lib" path="src/slf4j-simple-1.5.2.jar"/>   


    <classpathentry kind="lib" path="src/log4j-1.2.8.jar"/>   


    <classpathentry kind="lib" path="src/commons-dbcp-1.4.jar"/>   


    <classpathentry kind="lib" path="src/commons-pool-1.5.4.jar"/>   


    <classpathentry kind="lib" path="src/commons-collections-3.2.1.jar"/>   


    <classpathentry kind="lib" path="src/xbean-server-3.3.jar"/>  
<classpathentry kind="lib" path="src/activemq-all-5.5.0.jar"/>
	<classpathentry kind="lib" path="src/slf4j-api-1.5.2-sources.jar"/>
	<classpathentry kind="lib" path="src/slf4j-api-1.5.2.jar"/>
	<classpathentry kind="lib" path="src/slf4j-simple-1.5.2.jar"/>
	<classpathentry kind="lib" path="src/log4j-1.2.8.jar"/>
	<classpathentry kind="lib" path="src/commons-dbcp-1.4.jar"/>
	<classpathentry kind="lib" path="src/commons-pool-1.5.4.jar"/>
	<classpathentry kind="lib" path="src/commons-collections-3.2.1.jar"/>
	<classpathentry kind="lib" path="src/xbean-server-3.3.jar"/>

在Tomcat的conf目录下的context.xml配置中添加如下:

<Resource name="jms/ConnectionFactory"     

                auth="Container"     


                type="org.apache.activemq.ActiveMQConnectionFactory"  


                description="JMS Connection Factory"  


                factory="org.apache.activemq.jndi.JNDIReferenceFactory"  


                brokerURL="tcp://localhost:61616"  


                brokerName="LocalActiveMQBroker" />   

                   

    <Resource name="jms/Queue"     


                auth="Container"     


                type="org.apache.activemq.command.ActiveMQQueue"  


                description="My Queue"  


                factory="org.apache.activemq.jndi.JNDIReferenceFactory"  


                physicalName="TomcatQueue" />      
<Resource name="jms/ConnectionFactory"  
				auth="Container"  
				type="org.apache.activemq.ActiveMQConnectionFactory"
				description="JMS Connection Factory"
				factory="org.apache.activemq.jndi.JNDIReferenceFactory"
				brokerURL="tcp://localhost:61616"
				brokerName="LocalActiveMQBroker" />
				
	<Resource name="jms/Queue"  
				auth="Container"  
				type="org.apache.activemq.command.ActiveMQQueue"
				description="My Queue"
				factory="org.apache.activemq.jndi.JNDIReferenceFactory"
				physicalName="TomcatQueue" />

 配置如下:

<?xml version="1.0" encoding="UTF-8"?>   
<!--   
    Licensed to the Apache Software Foundation (ASF) under one or more   
    contributor license agreements.  See the NOTICE file distributed with   

    this work for additional information regarding copyright ownership.   


    The ASF licenses this file to You under the Apache License, Version 2.0  


    (the "License"); you may not use this file except in compliance with   

    the License.  You may obtain a copy of the License at   
      

    http://www.apache.org/licenses/LICENSE-2.0   

      
    Unless required by applicable law or agreed to in writing, software   

    distributed under the License is distributed on an "AS IS" BASIS,   

    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   

    See the License for the specific language governing permissions and   

    limitations under the License.   
-->   
<!-- START SNIPPET: xbean -->   
<beans    

  xmlns="http://www.springframework.org/schema/beans"    


  xmlns:amq="http://activemq.apache.org/schema/core"  


  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  


  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd   


  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">   

  <!-- 连接连接工厂 -->   

 <bean  id="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">   


     <property name="jndiName" value="java:comp/env/jms/ConnectionFactory"></property>   

 </bean>   
    
    

 <bean  id="tomcatQueue" class="org.springframework.jndi.JndiObjectFactoryBean">   


     <property name="jndiName" value="java:comp/env/jms/Queue"></property>   

 </bean>   
  
 <!-- 配置JMS的模板 -->   

<bean id="jmsTemplate"  class="org.springframework.jms.core.JmsTemplate">   


   <property name="connectionFactory" >   


     <ref  bean="jmsConnectionFactory"/>   

   </property>   

   <property name="defaultDestination">   


      <ref bean="tomcatQueue"/>   

   </property>   
</bean>   
  
  
<!-- 发送消息队列到目的地 -->   

<bean id="sender"  class="easyway.activemq.app.demo2.MessageSender">   


    <property name="jmsTemplate">   


       <ref bean="jmsTemplate"/>   

    </property>   
</bean>   
<!-- 接收消息 -->   

<bean id="receiver" class="easyway.activemq.app.demo2.MessageReceiver">   


    <property name="jmsTemplate">   


       <ref bean="jmsTemplate"/>   

    </property>   
</bean>   
  
  

<bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">   


   <property name="connectionFactory">   


      <ref bean="jmsConnectionFactory"/>   

   </property>   

   <property name="destination">   


      <ref bean="tomcatQueue"/>   

   </property>   

   <property name="messageListener">   


      <ref bean="receiver"/>   

    </property>   
</bean>   
  
</beans>  
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at
   
    http://www.apache.org/licenses/LICENSE-2.0
   
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!-- START SNIPPET: xbean -->
<beans 
  xmlns="http://www.springframework.org/schema/beans" 
  xmlns:amq="http://activemq.apache.org/schema/core"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">
  <!-- 连接连接工厂 -->
 <bean  id="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
     <property name="jndiName" value="java:comp/env/jms/ConnectionFactory"></property>
 </bean>
 
 
 <bean  id="tomcatQueue" class="org.springframework.jndi.JndiObjectFactoryBean">
     <property name="jndiName" value="java:comp/env/jms/Queue"></property>
 </bean>

 <!-- 配置JMS的模板 -->
<bean id="jmsTemplate"  class="org.springframework.jms.core.JmsTemplate">
   <property name="connectionFactory" >
     <ref  bean="jmsConnectionFactory"/>
   </property>
   <property name="defaultDestination">
      <ref bean="tomcatQueue"/>
   </property>
</bean>


<!-- 发送消息队列到目的地 -->
<bean id="sender"  class="easyway.activemq.app.demo2.MessageSender">
    <property name="jmsTemplate">
       <ref bean="jmsTemplate"/>
    </property>
</bean>
<!-- 接收消息 -->
<bean id="receiver" class="easyway.activemq.app.demo2.MessageReceiver">
    <property name="jmsTemplate">
       <ref bean="jmsTemplate"/>
    </property>
</bean>


<bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
   <property name="connectionFactory">
      <ref bean="jmsConnectionFactory"/>
   </property>
   <property name="destination">
      <ref bean="tomcatQueue"/>
   </property>
   <property name="messageListener">
      <ref bean="receiver"/>
    </property>
</bean>

</beans>

代码如下:

package easyway.activemq.app.demo2;   
  

import javax.jms.JMSException;   


import javax.jms.Message;   


import javax.jms.Session;   

  

import org.springframework.jms.core.JmsTemplate;   


import org.springframework.jms.core.MessageCreator;   

  

/**  
 * tomcat和activemq整合  
 * 消息发送者  
 * @author longgangbai  
 *  
 */  

public class MessageSender {   


  private JmsTemplate jmsTemplate;   

     
     

  public void send(final String text){   


      jmsTemplate.send(new MessageCreator(){   

  

        public Message createMessage(Session session) throws JMSException {   


            // TODO Auto-generated method stub   


            return session.createTextMessage(text);   

        }   
      });   
  }   
  
  

    public JmsTemplate getJmsTemplate() {   


        return jmsTemplate;   

    }   
       
       

    public void setJmsTemplate(JmsTemplate jmsTemplate) {   


        this.jmsTemplate = jmsTemplate;   

    }   
}  
package easyway.activemq.app.demo2;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

/**
 * tomcat和activemq整合
 * 消息发送者
 * @author longgangbai
 *
 */
public class MessageSender {
  private JmsTemplate jmsTemplate;
  
  
  public void send(final String text){
	  jmsTemplate.send(new MessageCreator(){

		public Message createMessage(Session session) throws JMSException {
			// TODO Auto-generated method stub
			return session.createTextMessage(text);
		}
	  });
  }


	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}
	
	
	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
}
package easyway.activemq.app.demo2;   
  

import javax.jms.JMSException;   


import javax.jms.Message;   


import javax.jms.MessageListener;   


import javax.jms.TextMessage;   

  

import org.springframework.jms.core.JmsTemplate;   


/**  
 * 消息接收者  
 * @author longgangbai  
 *  
 */  

public class MessageReceiver implements  MessageListener {   


    private JmsTemplate jmsTemplate;   

         

    public JmsTemplate getJmsTemplate() {   


        return jmsTemplate;   

    }   
  

    public void setJmsTemplate(JmsTemplate jmsTemplate) {   


        this.jmsTemplate = jmsTemplate;   

    }   

    public void receive() throws JMSException{   


         TextMessage text=(TextMessage)this.jmsTemplate.receive();   


        System.out.println("receive="+text.getText());   

    }   

    public void onMessage(Message message) {   


         if(message instanceof TextMessage){   

             TextMessage text=(TextMessage)message;   

             try {   

                System.out.println(text.getText());   

            } catch (Exception e) {   

            }   
         }   
    }   
       
}  
package easyway.activemq.app.demo2;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;
/**
 * 消息接收者
 * @author longgangbai
 *
 */
public class MessageReceiver implements  MessageListener {
	private JmsTemplate jmsTemplate;
	  
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
    public void receive() throws JMSException{
    	 TextMessage text=(TextMessage)this.jmsTemplate.receive();
		System.out.println("receive="+text.getText());
    }
	public void onMessage(Message message) {
		 if(message instanceof TextMessage){
			 TextMessage text=(TextMessage)message;
			 try {
				System.out.println(text.getText());
			} catch (Exception e) {
			}
		 }
	}
    
}
package easyway.activemq.app.demo2;   
  

import javax.jms.JMSException;   

  

import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;   


/**  
 * 测试类  
 * @author longgangbai  
 *  
 */  

public class MessageTest {   


    public void test() throws JMSException {   


        ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("app-activemq-tomcat.xml");   


        MessageSender sender=(MessageSender)ctx.getBean("sender");   


        MessageReceiver receive=(MessageReceiver)ctx.getBean("receiver");   


        sender.send("helloworld");   

        receive.receive();   
    }   
  
}  
package easyway.activemq.app.demo2;

import javax.jms.JMSException;

import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
/**
 * 测试类
 * @author longgangbai
 *
 */
public class MessageTest {
	public void test() throws JMSException {
		ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("app-activemq-tomcat.xml");
		MessageSender sender=(MessageSender)ctx.getBean("sender");
		MessageReceiver receive=(MessageReceiver)ctx.getBean("receiver");
		sender.send("helloworld");
		receive.receive();
	}

}

 index.jsp内容:

<%@ page language="java" import="easyway.activemq.app.demo2.*" pageEncoding="UTF-8"%>   
<%   
String path = request.getContextPath();   

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";   

%>   
  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   

<html>   
  <head>   

    <base href="<%=basePath%>">   

       

    <title>My JSP 'index.jsp' starting page</title>   


    <meta http-equiv="pragma" content="no-cache">   


    <meta http-equiv="cache-control" content="no-cache">   


    <meta http-equiv="expires" content="0">       


    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">   


    <meta http-equiv="description" content="This is my page">   

    <!--   

    <link rel="stylesheet" type="text/css" href="styles.css">   

    -->   
  </head>   
     
  <body>   
     
    <%   

        MessageTest message=new MessageTest();   

        message.test();   
     %>   
  <br>   
  </body>   
</html>  

相关推荐