首页 > 代码库 > activemq5.11整合spring4.2.3
activemq5.11整合spring4.2.3
前言
这篇博客记录 activemq5.11整合spring4.2.3的过程,免得以后忘记了
1、工程结构
2、pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jacky</groupId> <artifactId>activemq_spring4</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>activemq_spring4 Maven Webapp</name> <url>http://maven.apache.org</url> <!--<properties> <srping.version>4.1.0.RELEASE</srping.version> <log4j.version>1.2.17</log4j.version> </properties>--> <dependencyManagement> <dependencies> <dependency> <groupId>io.spring.platform </groupId> <artifactId>platform-bom</artifactId> <version>2.0.0.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <!-- <version>3.8.1</version>--> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <!-- <version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <!-- <version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <!--<version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <!--<version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <!--<version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <!-- <version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <!-- <version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <!--<version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <!--<version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <!--<version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <!--<version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <!--<version>${srping.version}</version>--> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-all</artifactId> <version>5.11.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <!--<version>4.1.5.RELEASE</version>--> </dependency> <dependency> <groupId>org.apache.xbean</groupId> <artifactId>xbean-spring</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <!-- <version>1.2</version>--> </dependency> </dependencies> <build> <finalName>activemq_spring4</finalName> </build> </project>
这里使用spring-io自动控制spring版本
3、ActiveMQ.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:amq="http://activemq.apache.org/schema/core" xmlns:jms="http://www.springframework.org/schema/jms" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.8.0.xsd"> <!-- ActiveMQ 连接工厂 --> <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供--> <!-- 如果连接网络:tcp://ip:61616;未连接网络:tcp://localhost:61616 以及用户名,密码--> <amq:connectionFactory id="amqConnectionFactory" brokerURL="tcp://127.0.0.1:61616" userName="admin" password="admin" /> <!-- Spring Caching连接工厂 --> <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory --> <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory"> <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory --> <property name="targetConnectionFactory" ref="amqConnectionFactory"></property> <!-- 同上,同理 --> <!-- <constructor-arg ref="amqConnectionFactory" /> --> <!-- Session缓存数量 --> <property name="sessionCacheSize" value="100" /> </bean> <!-- Spring JmsTemplate 的消息生产者 start--> <!-- 定义JmsTemplate的Queue类型 --> <bean id="jmsQueueTemplate" class="org.springframework.jms.core.JmsTemplate"> <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 --> <constructor-arg ref="connectionFactory" /> <!-- 非pub/sub模型(发布/订阅),即队列模式 --> <property name="pubSubDomain" value="false" /> </bean> <!-- 定义JmsTemplate的Topic类型 --> <bean id="jmsTopicTemplate" class="org.springframework.jms.core.JmsTemplate"> <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 --> <constructor-arg ref="connectionFactory" /> <!-- pub/sub模型(发布/订阅) --> <property name="pubSubDomain" value="true" /> </bean> <!--Spring JmsTemplate 的消息生产者 end--> <!-- 消息消费者 start--> <!-- 定义Queue监听器 --> <jms:listener-container destination-type="queue" container-type="default" connection-factory="connectionFactory" acknowledge="client"> <jms:listener destination="jacky.queue" ref="queueReceiver1"/> <jms:listener destination="jacky.queue" ref="queueReceiver2"/> </jms:listener-container> <!-- 定义Topic监听器 --> <jms:listener-container destination-type="topic" container-type="default" connection-factory="connectionFactory" acknowledge="auto"> <jms:listener destination="jacky.topic" ref="topicReceiver1"/> <jms:listener destination="jacky.topic" ref="topicReceiver2"/> </jms:listener-container> <!-- 消息消费者 end --> </beans>
4、applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- 查找最新的schemaLocation 访问 http://www.springframework.org/schema/ --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:amq="http://activemq.apache.org/schema/core" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.9.0.xsd"> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <!-- 配置扫描路径 --> <context:component-scan base-package="com.jacky"> <!-- 只扫描Service,也可以添加Repostory,但是要把Controller排除在外,Controller由spring-mvc.xml去加载 --> <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> --> <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" /> --> <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Component" /> --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
5、spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- 查找最新的schemaLocation 访问 http://www.springframework.org/schema/ --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 启用MVC注解 --> <mvc:annotation-driven /> <!-- 静态资源文件,不会被Spring MVC拦截 --> <mvc:resources location="/resources/" mapping="/resources/**"/> <!-- 指定Sping组件扫描的基本包路径 --> <context:component-scan base-package="com.jacky" > <!-- 这里只扫描Controller,不可重复加载Service --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- JSP视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> <!-- 定义其解析视图的order顺序为1 --> <property name="order" value="1" /> </bean> </beans>
6、log4j.properties
### direct log messages to stdout and logFile###
log4j.rootCategory=INFO, stdout,logFile
# OpenSymphony Stuff
log4j.logger.com.opensymphony=INFO
log4j.logger.org.apache.struts2=INFO
log4j.logger.org.apache.commons=INFO
# Spring Stuff
log4j.logger.org.springframework=INFO
log4j.logger.org.springframework.oxm=INFO
# Hibernate Stuff
log4j.logger.org.hibernate=INFO
log4j.logger.org.hibernate.type=INFO
log4j.logger.org.hibernate.tool.hbm2ddl=INFO
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[\u65F6\u95F4\:%d{yyyy-MM-dd hh\:mm\:ss}] [\u7EA7\u522B\:%p] [\u7C7B\:%c] [\u6D88\u606F\:%m] %n
log4j.appender.logFile=org.apache.log4j.RollingFileAppender
log4j.appender.logFile.File=D\:\\demo.log
log4j.appender.logFile.layout=org.apache.log4j.PatternLayout
log4j.appender.logFile.layout.ConversionPattern=[\u65F6\u95F4\:%d{yyyy-MM-dd hh\:mm\:ss}] [\u7EA7\u522B\:%p] [\u7C7B\:%c] [\u6D88\u606F\:%m] %n
log4j.appender.logFile.MaxFileSize = 5MB
log4j.appender.logFile.MaxBackupIndex =3
7、web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>activemq</display-name> <!-- Log4J Start --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param> <context-param> <param-name>log4jExposeWebAppRoot</param-name> <param-value>false</param-value> </context-param> <!-- Spring Log4J config --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- Log4J End --> <!-- Spring 编码过滤器 start --> <filter> <filter-name>characterEncoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring 编码过滤器 End --> <!-- Spring Application Context Listener Start --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml,classpath*:ActiveMQ.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring Application Context Listener End --> <!-- Spring MVC Config Start --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- Filter all resources --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Spring MVC Config End --> </web-app>
8、MqController.java
package com.jacky.controller; import com.jacky.mq.producer.queue.QueueSender; import com.jacky.mq.producer.topic.TopicSender; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; /** * Created by jacky on 2017/3/27 0027. */ @Controller @RequestMapping("/activemq") public class MqController { @Resource QueueSender queueSender; @Resource TopicSender topicSender; /** * 发送消息到队列 * Queue队列:仅有一个订阅者会收到消息,消息一旦被处理就不会存在队列中 * @param message * @return String */ @ResponseBody @RequestMapping("queueSender") public String queueSender(@RequestParam("message")String message){ String opt=""; try { queueSender.send("jacky.queue", message); opt = "suc"; } catch (Exception e) { opt = e.getCause().toString(); } return opt; } /** * 发送消息到主题 * Topic主题 :放入一个消息,所有订阅者都会收到 * 这个是主题目的地是一对多的 * @param message * @return String */ @ResponseBody @RequestMapping("topicSender") public String topicSender(@RequestParam("message")String message){ String opt = ""; try { topicSender.send("jacky.topic", message); opt = "suc"; } catch (Exception e) { opt = e.getCause().toString(); } return opt; } }
9、QueueReceiver1.java
package com.jacky.mq.consumer.queue; import org.springframework.stereotype.Component; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; /** * 监听消息队列 */ @Component public class QueueReceiver1 implements MessageListener{ @Override public void onMessage(Message message) { try { System.out.println("QueueReceiver1接收到消息:"+((TextMessage)message).getText()); message.acknowledge();//手动向broker确认接收成功,如果发生异常,就不反回ack } catch (JMSException e) { e.printStackTrace(); } } }
10、QueueReceiver2.java
package com.jacky.mq.consumer.queue; import org.springframework.stereotype.Component; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; /** * Created by Administrator on 2017/3/27 0027. */ @Component public class QueueReceiver2 implements MessageListener { @Override public void onMessage(Message message) { try { System.out.println("QueueReceiver2接收到消息:"+((TextMessage)message).getText()); message.acknowledge();////手动向broker确认接收成功,如果发生异常,就不反回ack } catch (JMSException e) { e.printStackTrace(); } } }
11、TopicReceiver1.java
package com.jacky.mq.consumer.topic; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import org.springframework.stereotype.Component; /** * * @author liang * @description Topic消息监听器 * */ @Component public class TopicReceiver1 implements MessageListener{ @Override public void onMessage(Message message) { try { System.out.println("TopicReceiver1接收到消息:"+((TextMessage)message).getText()); } catch (JMSException e) { e.printStackTrace(); } } }
12、TopicReceiver2.java
package com.jacky.mq.consumer.topic; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import org.springframework.stereotype.Component; /** * * @author liang * @description Topic消息监听器 * */ @Component public class TopicReceiver2 implements MessageListener{ @Override public void onMessage(Message message) { try { System.out.println("TopicReceiver2接收到消息:"+((TextMessage)message).getText()); } catch (JMSException e) { e.printStackTrace(); } } }
13、QueueSender.java
package com.jacky.mq.producer.queue; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import org.springframework.stereotype.Component; /** * * @author liang * @description 队列消息生产者,发送消息到队列 * */ @Component("queueSender") public class QueueSender { @Autowired @Qualifier("jmsQueueTemplate") private JmsTemplate jmsTemplate;//通过@Qualifier修饰符来注入对应的bean /** * 发送一条消息到指定的队列(目标) * @param queueName 队列名称 * @param message 消息内容 */ public void send(String queueName,final String message){ jmsTemplate.send(queueName, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage(message); } }); } }
14、TopicSender.java
package com.jacky.mq.producer.topic; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import org.springframework.stereotype.Component; /** * * @author liang * @description Topic生产者发送消息到Topic * */ @Component("topicSender") public class TopicSender { @Autowired @Qualifier("jmsTopicTemplate") private JmsTemplate jmsTemplate; /** * * @param topicName * @param message */ public void send(String topicName,final String message){ jmsTemplate.send(topicName, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage(message); } }); } }
15、index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); System.out.println(path); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; System.out.println(basePath); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="http://www.mamicode.com/"> <title>ActiveMQ Demo程序</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <script type="text/javascript" src="http://www.mamicode.com/resources/jquery-1.11.0.min.js"></script> <style type="text/css"> .h1 { margin: 0 auto; } #producer{ width: 48%; border: 1px solid blue; height: 80%; align:center; margin:0 auto; } body{ text-align :center; } div { text-align :center; } textarea{ width:80%; height:100px; border:1px solid gray; } button{ background-color: rgb(62, 156, 66); border: none; font-weight: bold; color: white; height:30px; } </style> <script type="text/javascript"> function send(controller){ if($("#message").val()==""){ $("#message").css("border","1px solid red"); return; }else{ $("#message").css("border","1px solid gray"); } $.ajax({ type: ‘post‘, url:‘<%=basePath%>activemq/‘+controller, dataType:‘text‘, data:{"message":$("#message").val()}, success:function(data){ if(datahttp://www.mamicode.com/=="suc"){ $("#status").html("<font color=green>发送成功</font>"); setTimeout(clear,1000); }else{ $("#status").html("<font color=red>"+data+"</font>"); setTimeout(clear,5000); } }, error:function(data){ $("#status").html("<font color=red>ERROR:"+data["status"]+","+data["statusText"]+"</font>"); setTimeout(clear,5000); } }); } function clear(){ $("#status").html(""); } </script> </head> <body> <h1>Hello ActiveMQ</h1> <div id="producer"> <h2>Producer</h2> <textarea id="message"></textarea> <br> <button onclick="send(‘queueSender‘)">发送Queue消息</button> <button onclick="send(‘topicSender‘)">发送Topic消息</button> <br> <span id="status"></span> </div> </body> </html>
github地址:https://github.com/jacky-lulu/activemq5_spring4
activemq5.11整合spring4.2.3
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。