本文主要想通过一个WEB示例展示ActiveMQ在具体应用程序中是如何使用的,顺便简单介绍以下如何通过Eclipse搭建一个SpringMVC框架和Maven项目开发框架。下面首先展示一下项目最终的运行效果:
首先在浏览器网址栏输入网址:http://127.0.0.1:8080/activeMQSpring/welcome 页面显示如下:
然后点击Send Messages 进入消息发送界面:
点击Submit按钮将会将MessageText框中当前时间发送给ActiveMQ服务器并返回至Welcome界面,点击RETURN HOME 将直接返回到Welcome界面。
当点击Submit后,页面将直接跳转至Welcome界面,然后点击Get Message From Queue,将会从ActiveMQ服务器中获取一条消息:
从图中可以看出,获得的消息正好是刚才发送的消息。
下面展示一下项目结构:
本示例开发环境:
- 开发工具:Eclipse Neon Release (4.6.0)
- jdk: 1.7.0_79
- Spring framework 版本:4.3.6.RELEASE
- ActiveMQ 版本:5.14.3
- Jboss 版本:jboss-as-7.1.1.Final
Maven+Spring框架搭建
Maven+Spring框架搭建的基本思想是首先大家Maven Web开发框架,然后通过Maven pom.xml文件引入Spring MVC框架所需要的依赖包。
首先打开Eclipse,新建Maven项目:
选择 Maven Project,点击next:
选择 Use Default WorkSpace Location,点击next:
Catalog选择“All Catalogs”,在下面的大选择框里面选择“org.apache.maven.archetypes maven-archetype-webapp 1.0”,点击next:
由于Maven项目是可以采用三维坐标(groupid、artifactid and version)来确定具体项目的,所以,这三个信息为必填项。填写完成后点击Finish,此时在Project Explorer 中出现了我们刚刚新建的activeMQSpring项目。
右键点击项目,选择“Properties”:
在左侧选择框中选择“Java Build Path”,在右侧选择“Order and Export”,发现出现了两个相同的错误:activeMQSpring/src/main/java和activeMQSpring/src/test/java missing,由于我们要在activeMQSpring/src/main/java路径下写java文件,所以这个问题必须解决,解决方案如下:
在“Java Build Path” 中选择 “Source”,在地下选择框中选择报错的那两个文件路径选项,点击“ Allow output folders for source folders ”前面的单选框,点击Apply,点击OK,此时,我们可以从项目结构中对应路径下看到缺失的两个文件夹。
右键点击项目,选择Properties,在Properties中左侧栏选择“Java Compiler”,将左侧栏中的可选择的信息修改成1.7,点击OK。
到目前为止,Maven框架搭建完成。
下面通过Maven pom.xml文件实现Spring MVC 开发环境的搭建,编辑pom.xml文件内容如下:
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>com.unionpay.demo</groupId> 5 <artifactId>activeMQSpring</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>activeMQSpring Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 11 12 <properties> 13 <springframework>4.3.6.RELEASE</springframework> 14 </properties> 15 16 17 <dependencies> 18 <dependency> 19 <groupId>junit</groupId> 20 <artifactId>junit</artifactId> 21 <version>3.8.1</version> 22 <scope>test</scope> 23 </dependency> 24 25 26 <dependency> 27 <groupId>jstl</groupId> 28 <artifactId>jstl</artifactId> 29 <version>1.2</version> 30 </dependency> 31 32 <dependency> 33 <groupId>javax.servlet</groupId> 34 <artifactId>javax.servlet-api</artifactId> 35 <version>3.1.0</version> 36 </dependency> 37 38 <!-- spring --> 39 40 <dependency> 41 <groupId>org.springframework</groupId> 42 <artifactId>spring-core</artifactId> 43 <version>${springframework}</version> 44 </dependency> 45 46 <dependency> 47 <groupId>org.springframework</groupId> 48 <artifactId>spring-context</artifactId> 49 <version>${springframework}</version> 50 </dependency> 51 52 <dependency> 53 <groupId>org.springframework</groupId> 54 <artifactId>spring-tx</artifactId> 55 <version>${springframework}</version> 56 </dependency> 57 58 <dependency> 59 <groupId>org.springframework</groupId> 60 <artifactId>spring-webmvc</artifactId> 61 <version>${springframework}</version> 62 </dependency> 63 64 <dependency> 65 <groupId>org.springframework</groupId> 66 <artifactId>spring-web</artifactId> 67 <version>${springframework}</version> 68 </dependency> 69 70 <dependency> 71 <groupId>org.springframework</groupId> 72 <artifactId>spring-jms</artifactId> 73 <version>${springframework}</version> 74 </dependency> 75 76 77 <!-- xbean --> 78 79 <dependency> 80 <groupId>org.apache.xbean</groupId> 81 <artifactId>xbean-spring</artifactId> 82 <version>3.16</version> 83 </dependency> 84 85 <dependency> 86 <groupId>com.thoughtworks.xstream</groupId> 87 <artifactId>xstream</artifactId> 88 <version>1.3.1</version> 89 </dependency> 90 91 <!-- activemq --> 92 93 <dependency> 94 <groupId>org.apache.activemq</groupId> 95 <artifactId>activemq-all</artifactId> 96 <version>5.14.3</version> 97 </dependency> 98 99 </dependencies> 100 <build> 101 <finalName>activeMQSpring</finalName> 102 </build> 103 </project>
编写完成后进行保存,然后右键项目,选择“Maven”->"Update Project":
选择项目,点击OK。然后就可以在项目结构中看到项目中已经包含了开发所需要的Spring依赖包:
这时,Spring MVC所需的jar包引用也已经完成啦。
下面编写web.xml配置文件,内容如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 3 <display-name>activeMQSpring</display-name> 4 <!-- contextConfigLocation 参数定义了要装入的 Spring 配置文件。 --> 5 <context-param> 6 <param-name>contextConfigLocation</param-name> 7 <param-value> 8 classpath:spring-root.xml; 9 classpath:activemq.xml 10 </param-value> 11 </context-param> 12 13 14 <listener> 15 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 16 </listener> 17 18 <servlet> 19 <servlet-name>springMVC</servlet-name> 20 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 21 <init-param> 22 <param-name>contextConfigLocation</param-name> 23 <param-value>classpath:spring-mvc-dispatch.xml</param-value> 24 </init-param> 25 <load-on-startup>1</load-on-startup> 26 </servlet> 27 28 <servlet-mapping> 29 <servlet-name>springMVC</servlet-name> 30 <url-pattern>/</url-pattern> 31 </servlet-mapping> 32 33 34 <filter> 35 <filter-name>characterEncodingFilter</filter-name> 36 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 37 <init-param> 38 <param-name>encoding</param-name> 39 <param-value>UTF-8</param-value> 40 </init-param> 41 <init-param> 42 <param-name>forceRequestEncoding</param-name> 43 <param-value>true</param-value> 44 </init-param> 45 <init-param> 46 <param-name>forceResponseEncoding</param-name> 47 <param-value>true</param-value> 48 </init-param> 49 </filter> 50 51 <filter-mapping> 52 <filter-name>characterEncodingFilter</filter-name> 53 <url-pattern>/*</url-pattern> 54 </filter-mapping> 55 56 57 </web-app>
编写spring-mvc-dispatch.xml文件,内容如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-4.1.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> 12 13 <!-- 将base-package 目录下java文件中的所有@Component @Controller@Service等这些注解的类,则把这些类注册为bean --> 14 <context:component-scan base-package="com.unionpay.demo.mvc.controller" /> 15 <!-- 自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的。 --> 16 <mvc:annotation-driven /> 17 18 <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> 19 <property name="viewClass" 20 value="org.springframework.web.servlet.view.JstlView" /> 21 <property name="prefix" value="/WEB-INF/views/" /> 22 <property name="suffix" value=".jsp" /> 23 </bean> 24 </beans>
下面编写activemq.xml文件,内容如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:amq="http://activemq.apache.org/schema/core" 5 xmlns:jms="http://www.springframework.org/schema/jms" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:mvc="http://www.springframework.org/schema/mvc" 8 xsi:schemaLocation=" 9 http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 11 http://www.springframework.org/schema/context 12 http://www.springframework.org/schema/context/spring-context-4.1.xsd 13 http://www.springframework.org/schema/mvc 14 http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd 15 http://www.springframework.org/schema/jms 16 http://www.springframework.org/schema/jms/spring-jms-4.1.xsd 17 http://activemq.apache.org/schema/core 18 http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd" 19 > 20 21 <context:component-scan base-package="com.unionpay.demo.activemq" /> 22 <mvc:annotation-driven /> 23 24 <amq:connectionFactory id="amqConnectionFactory" 25 brokerURL="tcp://127.0.0.1:61616" 26 userName="admin" 27 password="admin" /> 28 29 <!-- 配置JMS连接工长 --> 30 <bean id="connectionFactory" 31 class="org.springframework.jms.connection.CachingConnectionFactory"> 32 <constructor-arg ref="amqConnectionFactory" /> 33 <property name="sessionCacheSize" value="100" /> 34 </bean> 35 36 <!-- 定义消息队列(Queue) --> 37 <bean id="demoQueueDestination" class="org.apache.activemq.command.ActiveMQQueue"> 38 <!-- 设置消息队列的名字 --> 39 <constructor-arg> 40 <value>unionpay.demo</value> 41 </constructor-arg> 42 </bean> 43 44 <!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 --> 45 <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> 46 <property name="connectionFactory" ref="connectionFactory" /> 47 <property name="defaultDestination" ref="demoQueueDestination" /> 48 <property name="receiveTimeout" value="10000" /> 49 <!-- true是topic,false是queue,默认是false,此处显示写出false --> 50 <property name="pubSubDomain" value="false" /> 51 </bean> 52 53 <bean id="producerService" class="com.unionpay.demo.activemq.producer.ProducerService"> 54 </bean> 55 56 <bean id="consumerService" class="com.unionpay.demo.activemq.consumer.ConsumerService"> 57 </bean> 58 59 </beans>
下面在目录/src/main/java下建立三个Package包: “com.unionpay.demo.activemq.producer”、 "com.unionpay.demo.activemq.consumer"、 "com.unionpay.demo.mvc.controller":
建立完成后会在src/main/java/目录下看见这三个包:
然后在“....producer”包中新建类ProducerService.java,内容如下:
1 package com.unionpay.demo.activemq.producer; 2 3 import javax.annotation.Resource; 4 import javax.jms.Destination; 5 import javax.jms.JMSException; 6 import javax.jms.Message; 7 import javax.jms.Session; 8 9 import org.springframework.jms.core.JmsTemplate; 10 import org.springframework.jms.core.MessageCreator; 11 import org.springframework.stereotype.Service; 12 13 @Service 14 public class ProducerService { 15 16 @Resource(name="jmsTemplate") 17 private JmsTemplate jmsTemplate; 18 19 20 public void sendMessage(Destination destination,final String msg){ 21 System.out.println("Send " + msg + " to Destination " + destination.toString()); 22 23 MessageCreator messageCreator = new MessageCreator(){ 24 25 public Message createMessage(Session session) throws JMSException { 26 27 return session.createTextMessage(msg); 28 } 29 30 }; 31 32 jmsTemplate.send(destination, messageCreator); 33 } 34 35 36 public void sendMessage(final String msg){ 37 38 String destination = jmsTemplate.getDefaultDestinationName().toString(); 39 System.out.println("Send " + msg + " to Destination " + destination); 40 MessageCreator messageCreator = new MessageCreator(){ 41 42 public Message createMessage(Session session) throws JMSException { 43 // TODO Auto-generated method stub 44 return session.createTextMessage(msg); 45 } 46 47 }; 48 49 jmsTemplate.send(messageCreator); 50 } 51 }
然后在“....consumer”包中添加类文件ConsumerService.java,内容如下:
1 package com.unionpay.demo.activemq.consumer; 2 3 import javax.annotation.Resource; 4 import javax.jms.Destination; 5 import javax.jms.JMSException; 6 import javax.jms.TextMessage; 7 8 import org.springframework.jms.core.JmsTemplate; 9 import org.springframework.stereotype.Service; 10 11 @Service 12 public class ConsumerService { 13 14 @Resource(name = "jmsTemplate") 15 private JmsTemplate jmsTemplate; 16 17 public TextMessage receive(Destination destination) { 18 TextMessage tm = (TextMessage) jmsTemplate.receive(destination); 19 if (tm != null) { 20 try { 21 System.out.println("Get Message: " + tm.getText() + " from Destination " + destination.toString()); 22 } catch (JMSException e) { 23 e.printStackTrace(); 24 } 25 } 26 return tm; 27 } 28 29 }
然后在“...mvc.controller”包中添加WelcomeController.java文件,内容如下:
1 package com.unionpay.demo.mvc.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RequestMethod; 6 import org.springframework.web.servlet.ModelAndView; 7 8 @Controller 9 public class WelcomeController { 10 11 @RequestMapping(value="/welcome",method=RequestMethod.GET) 12 public ModelAndView welcome(){ 13 System.out.println("-------------welcome-----------"); 14 ModelAndView mv = new ModelAndView(); 15 mv.setViewName("welcome"); 16 return mv; 17 } 18 }
然后在“....mvc.controller”包中添加类DemoController.java,内容如下:
1 package com.unionpay.demo.mvc.controller; 2 3 import java.io.IOException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 import javax.annotation.Resource; 8 import javax.jms.Destination; 9 import javax.jms.JMSException; 10 import javax.jms.TextMessage; 11 import javax.management.MBeanServerConnection; 12 import javax.management.remote.JMXConnector; 13 import javax.management.remote.JMXConnectorFactory; 14 import javax.management.remote.JMXServiceURL; 15 16 import org.springframework.stereotype.Controller; 17 import org.springframework.web.bind.annotation.RequestMapping; 18 import org.springframework.web.bind.annotation.RequestMethod; 19 import org.springframework.web.bind.annotation.RequestParam; 20 import org.springframework.web.servlet.ModelAndView; 21 22 import com.unionpay.demo.activemq.consumer.ConsumerService; 23 import com.unionpay.demo.activemq.producer.ProducerService; 24 25 @Controller 26 public class DemoController { 27 28 @Resource(name = "demoQueueDestination") 29 private Destination demoQueueDestination; 30 31 @Resource(name = "producerService") 32 private ProducerService producer; 33 34 @Resource(name = "consumerService") 35 private ConsumerService consumer; 36 37 @RequestMapping(value = "/producer", method = RequestMethod.GET) 38 public ModelAndView producer() { 39 System.out.println("--------------go producer"); 40 41 Date now = new Date(); 42 43 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 44 45 String time = sdf.format(now); 46 47 System.out.println(time); 48 49 ModelAndView mv = new ModelAndView(); 50 51 mv.addObject("time", time); 52 mv.setViewName("jms_producer"); 53 return mv; 54 } 55 56 @RequestMapping(value = "/onsend", method = RequestMethod.POST) 57 public ModelAndView producer(@RequestParam("message") String message) { 58 System.out.println("---------send to jms"); 59 ModelAndView mv = new ModelAndView(); 60 producer.sendMessage(demoQueueDestination, message); 61 mv.setViewName("welcome"); 62 return mv; 63 } 64 65 @RequestMapping(value = "/receive", method = RequestMethod.GET) 66 public ModelAndView queue_receive() throws JMSException { 67 System.out.println("-----------receive message"); 68 ModelAndView mv = new ModelAndView(); 69 70 TextMessage tm = consumer.receive(demoQueueDestination); 71 72 if (tm == null) { 73 mv.addObject("textMessage", "Queue is Empty"); 74 } else { 75 mv.addObject("textMessage", tm.getText()); 76 } 77 mv.setViewName("jms_receiver"); 78 return mv; 79 } 80 81 public ModelAndView jmsManager() throws IOException { 82 System.out.println("--------------jms manager"); 83 ModelAndView mv = new ModelAndView(); 84 85 mv.setViewName("welcome"); 86 87 JMXServiceURL url = new JMXServiceURL(""); 88 89 JMXConnector connector = JMXConnectorFactory.connect(url); 90 connector.connect(); 91 MBeanServerConnection connection = connector.getMBeanServerConnection(); 92 93 return mv; 94 } 95 96 }
在Spring MVC中,Model 和 Controller 部分我们已经编写完成,下面就该编写View部分了。
在WEB-INF目录下新建views文件夹,然后在该文件夹中添加welcome.jsp文件:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Welcome</title> 8 </head> 9 <body> 10 11 <h1>Welcome!!!</h1> 12 <h2><a href="producer">Send Messages</a></h2> 13 <h2><a href="receive">Get Message From Queue</a></h2> 14 </body> 15 </html>
在views文件夹下添加jms_producer.jsp文件:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>JMS-Producer</title> 8 </head> 9 <body> 10 11 <h1>JMS-Producer!!!</h1> 12 <form action="onsend" method="post"> 13 MessageText:<textarea name="message">${time}</textarea> 14 <input type="submit" value="Submit"> 15 </form> 16 17 <h2><a href="welcome">RETURN HOME</a></h2> 18 19 </body> 20 </html>
在views目录下添加jms_receiver.jsp文件:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>JMS-Reciever</title> 8 </head> 9 <body> 10 <h1>JMS-Recever!!!</h1> 11 <h2>${textMessage}</h2> 12 <h2><a href="welcome">RETURN HOME</a></h2> 13 </body> 14 </html>
到目前为止,整个项目建立完成。
那么下面将该项目添加到Jboss容器中,具体操作过程这里就不介绍啦,很简单的。
然后启动activeMQ服务器:
然后通过Eclipse启动Jboss服务器,启动成功后终端显示如下:
出现"Deployed "activeMQSpring.war" "说明部署成功,下面在浏览器中输入网址:http://127.0.0.1:8080/activeMQSpring/welcome,显示welcome界面,与本文开始项目展示描述一致,说明项目运行成功啦。
源代码下载:activeMQSpring.zip
参考文献