ActiveMQ与tomcat和spring mvc搭建

来源:互联网 发布:互联网大数据时代论文 编辑:程序博客网 时间:2024/05/18 01:47

所用软件版本:

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  {    @Overridepublic 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 {@Autowiredprivate 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

1 0
原创粉丝点击