ActiveMQ與tomcat和spring mvc搭建

所用軟件版本:

tomcat:apache-tomcat-7.0.54

spring:spring-framework-4.0.6

activemq:apache-activemq-5.10.0

所需jar包:

代碼結構:


一、首先搭建一個spring mvc環境

(1)web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- Spring MVC配置 -->  
<!-- ====================================== -->  
<servlet>  
    <servlet-name>spring</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <!-- 可以自定義servlet.xml配置文件的位置和名稱,默認爲WEB-INF目錄下,名稱爲[<servlet-name>]-servlet.xml,如spring-servlet.xml -->   
    <init-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:config/spring-servlet.xml</param-value>  默認  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
</servlet>  
  
<servlet-mapping>  
    <servlet-name>spring</servlet-name>  
    <url-pattern>/</url-pattern>  
</servlet-mapping>  
  
<!-- Spring配置 -->  
<!-- ====================================== -->  
<listener>  
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
</listener>  
<!-- 指定Spring Bean的配置文件所在目錄。默認配置在WEB-INF目錄下 -->  
<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>classpath:config/applicationContext.xml</param-value>  
</context-param>  
</web-app>
(2)spring-servlet.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    
    http://www.springframework.org/schema/tx    
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd   
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-4.0.xsd 
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
    http://www.springframework.org/schema/mvc   
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-4.0.xsd">

	<!-- Spring MVC配置 -->
    <context:annotation-config />
    <!--掃描註解 -->
    <context:component-scan base-package="org.mq.controller" />
    <!--默認的mvc註解映射的支持 -->
    <mvc:annotation-driven/>
    <!-- 支持異步方法執行 -->
    <task:annotation-driven /> 

    <!-- 視圖解析器和json解析器 -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <entry key="html" value="text/html"/>
                <entry key="json" value="application/json"/>
            </map>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/jsp/" /> <!--可爲空,方便實現自已的依據擴展名來選擇視圖解釋類的邏輯 -->
                    <property name="suffix" value=".jsp"/>
                </bean>
            </list>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
            </list>
        </property>
    </bean>

    <!-- 總錯誤處理 -->
    <bean id="exceptionResolver"
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView">
            <value>/error</value>
        </property>
        <property name="defaultStatusCode">
            <value>500</value>
        </property>
        <property name="warnLogCategory">
            <value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver
            </value>
        </property>
    </bean>
</beans>  


(3)applicationContext.xml配置(主要是activeMQ相關配置):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    
    http://www.springframework.org/schema/tx    
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd   
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-4.0.xsd 
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
    http://www.springframework.org/schema/mvc   
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-4.0.xsd
    http://activemq.apache.org/schema/core
    http://activemq.apache.org/schema/core/activemq-core.xsd">
	
	<!-- 消息監聽容器 -->  
	<bean id="listenerContainer"  
        class="org.springframework.jms.listener.DefaultMessageListenerContainer">  
        <property name="connectionFactory" ref="connectionFactory"></property>  
        <property name="destination" ref="messageQueue"></property>  
        <property name="messageListener" ref="receiveMessageListener"></property>  
    </bean>  
    
    <!-- JMS PTP MODEL -->  
    <!-- PTP鏈接工廠 -->  
    <bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">  
        <property name="jndiName" value="java:comp/env/myJMS/ConnectionFactory"></property>  
    </bean>  
    
    <!-- 定義消息隊列 -->
    <bean id="messageQueue" class="org.springframework.jndi.JndiObjectFactoryBean">  
        <property name="jndiName" value="java:comp/env/myJMS/MessageQueue"></property>  
    </bean>  
    
    <!-- 消息發送方 -->  
    <bean id="messageSender" class="org.mq.controller.MessageSender">  
        <property name="jmsTemplate" ref="jmsTemplate"></property>  
    </bean>  
    
    <!-- 消息接收方 -->  
    <bean id="receiveMessageListener"  class="org.mq.controller.ReceiveMessageListener"></bean>  
        
    <!-- PTP jms模板 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
        <property name="connectionFactory" ref="connectionFactory"></property>  
        <property name="defaultDestination" ref="messageQueue"></property>  
        <!-- false-p2p  true-p2s -->
        <property name="pubSubDomain" value="false" /> 
    </bean>  
</beans>  

消息隊列的定義中用到了jndiName,其值得配置與tomcat的context.xml中配置需保持一致。

(4)tomcat的context.xml中的配置:

<?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.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->

	<Resource name="myJMS/ConnectionFactory"   
		auth="Container"     
		type="org.apache.activemq.ActiveMQConnectionFactory"   
		description="JMS Connection Factory"  
		factory="org.apache.activemq.jndi.JNDIReferenceFactory"   
		brokerURL="tcp://localhost:61616"   
		brokerName="MyActiveMQBroker"/>  
  
	<Resource name="myJMS/MessageQueue"   
		auth="Container"   
		type="org.apache.activemq.command.ActiveMQQueue"  
		description="My Message Queue"  
		factory="org.apache.activemq.jndi.JNDIReferenceFactory"   
		physicalName="MyMessageQueue"/> 
	
</Context>


其中brokerURL的地址爲需要連接的activeMQ消息服務地址,需與實際情況中地址保持一致,默認本地市tcp://localhost:61616,否則啓動時,spring會不斷的去連接brokerURL所代表的消息服務時,會一直提示無法連接JMS服務。


二、消息接收器與發送器

(1)接收器:

package org.mq.controller;

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

public class ReceiveMessageListener implements MessageListener  {
    
	@Override
	public void onMessage(Message message) {
		 if (message instanceof TextMessage) {  
	            TextMessage text = (TextMessage) message;  
	            try {  
	                System.out.println("Received message:" + text.getText());  
	            } catch (JMSException e) {  
	                e.printStackTrace();  
	            }  
	        }  
		
	}  
}

(2)發送器:

package org.mq.controller;

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

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

public class MessageSender {
	
    private JmsTemplate jmsTemplate;  
  
    public void setJmsTemplate(JmsTemplate jmsTemplate) {  
        this.jmsTemplate = jmsTemplate;  
    }  
      
    public void sendMessage(final String message) {  
        System.out.println("Send message: " + message);  
        jmsTemplate.send(new MessageCreator() {  
        	@Override
            public Message createMessage(Session session) throws JMSException {  
                TextMessage textMessage = session.createTextMessage(message);  
                return textMessage;  
            }
        });  
    }  
}



三、請求處理controller:

package org.mq.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/send")
public class SendMessageController {

	@Autowired
	private MessageSender messageSender;  
  
	@RequestMapping("sendMsg.do")
    public ModelAndView sendMessage(HttpServletRequest request,  HttpServletResponse response) throws Exception {  
        
		System.out.println("enter sendMessage ");
		
        String message = request.getParameter("message");  
        messageSender.sendMessage(message);  
        
        ModelAndView mav = new ModelAndView();
        mav.setViewName("success");
        return mav;  
    }  
}

四、消息請求頁面:

<%@ page language="java" import="java.util.*" 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>
    <div align="center" style="width: 500px; height: 300px; border:2px; borderColor:black">  
            <form action="send/sendMsg.do" method="post">  
                <table align="center">  
                    <tr>  
                        <th colspan="2">  
                            消息發送控制檯  
                        </th>  
                    </tr>  
                    <tr>  
                        <td>  
                            消息內容:  
                        </td>  
                        <td>  
                            <input type="text" name="message">  
                        </td>  
                    </tr>  
                    <tr>  
                        <td align="center" colspan="2">  
                            <input type="reset" value="清除">  
                                  
                            <input type="submit" value="發送">  
                        </td>  
                    </tr>  
                </table>  
            </form>  
        </div>  
  </body>
</html>

五、成功頁面:

<%@ page language="java" import="java.util.*" 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>結果</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>
    send success<br>
  </body>
</html>

六:啓動服務

服務需要啓動兩個:

1.activeMQ服務(詳見http://blog.csdn.net/wlsyn/article/details/37934071)

2.spring自身項目服務


結果如下所示,前臺頁面發送的消息在後臺可以全部接收:




源碼下載地址:

http://download.csdn.net/detail/yangjun19890825/7650713

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章