spring与actionMQ整合
出处:http://www.cnblogs.com/leiOOlei/p/5075402.html
一、配置部分
ActiveMQ的安装这就不说了,很简单,
这个例子采用maven构建,首先看一下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.gzframe.demo</groupId>
<artifactId>gzframe</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>gzframe Maven Webapp</name>
<url>http://maven.apache.org</url> <!-- 版本管理 -->
<properties>
<springframework>4.1.8.RELEASE</springframework>
<javax.servlet>3.1.0</javax.servlet>
</properties> <dependencies> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${javax.servlet}</version>
</dependency> <!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${springframework}</version>
</dependency>
<!-- xbean 如<amq:connectionFactory /> -->
<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>3.16</version>
</dependency> <!-- activemq -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-core</artifactId>
<version>5.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.12.1</version>
</dependency> </dependencies> <build>
<finalName>gzframe</finalName>
</build>
</project>
接下来看一下web.xml,如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- 加载spring的配置文件,例如hibernate、jms等集成 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring-root.xml;
classpath:activemq.xml;
</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <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-dispatch.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 处理编码格式 -->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>
其中spring-root.xml 很简单,负责加载一些spring的配置
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <context:component-scan base-package="com.gzframe.demo.entity" />
<mvc:annotation-driven /> </beans>
spring-mvc-dispatch.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <context:component-scan base-package="com.gzframe.demo.mvc.controller" />
<mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
activemq.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:amq="http://activemq.apache.org/schema/core"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms-4.1.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd"
> <context:component-scan base-package="com.gzframe.demo.activemq" />
<mvc:annotation-driven /> <amq:connectionFactory id="amqConnectionFactory"
brokerURL="tcp://192.168.150.61:61616"
userName="admin"
password="admin" /> <!-- 配置JMS连接工长 -->
<bean id="connectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
<property name="sessionCacheSize" value="100" />
</bean> <!-- 定义消息队列(Queue) -->
<bean id="demoQueueDestination" class="org.apache.activemq.command.ActiveMQQueue">
<!-- 设置消息队列的名字 -->
<constructor-arg>
<value>gzframe.demo</value>
</constructor-arg>
</bean> <!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="demoQueueDestination" />
<property name="receiveTimeout" value="10000" />
<!-- true是topic,false是queue,默认是false,此处显示写出false -->
<property name="pubSubDomain" value="false" />
</bean>
</beans>
二、代码部分
消息生产者ProducerService.java,代码如下
package com.gzframe.demo.activemq.producer; import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session; import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service; @Service
public class ProducerService { @Resource(name="jmsTemplate")
private JmsTemplate jmsTemplate; /**
* 向指定队列发送消息
*/
public void sendMessage(Destination destination, final String msg) {
System.out.println("向队列" + destination.toString() + "发送了消息------------" + msg);
jmsTemplate.send(destination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(msg);
}
});
} /**
* 向默认队列发送消息
*/
public void sendMessage(final String msg) {
String destination = jmsTemplate.getDefaultDestination().toString();
System.out.println("向队列" +destination+ "发送了消息------------" + msg);
jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(msg);
}
}); } }
消费者ConsumerService.java,代码如下
package com.gzframe.demo.activemq.consumer; import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage; import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service; @Service
public class ConsumerService { @Resource(name="jmsTemplate")
private JmsTemplate jmsTemplate; /**
* 接收消息
*/
public TextMessage receive(Destination destination) {
TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
try {
System.out.println("从队列" + destination.toString() + "收到了消息:\t"
+ tm.getText());
} catch (JMSException e) {
e.printStackTrace();
} return tm; } }
三、页面部分
1.首先写一个欢迎页,welcome.jsp如下,
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome</title>
</head>
<body>
<h1>Welcome!!!</h1>
<h2><a href="producer">去发消息</a></h2>
<h2><a href="receive">从队列中取一个消息</a></h2>
</body>
</html>
2.然后是生产者页面jms_producer.jsp,如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JMS-Producer</title>
</head>
<body>
<h1>JMS-Producer!!!</h1>
<form action="onsend" method="post"> MessageText:<textarea name="message">${time }</textarea> <input type="submit" value="提交" />
</form>
<h2><a href="welcome">返回主页</a></h2>
</body>
</html>
3.接收者页面queue_receive.jsp,如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Receive</title>
</head>
<body>
<h1>${textMessage }</h1>
<h2><a href="welcome">返回主页</a></h2>
</body>
</html>
四、Controller控制器
1.首先controller到首页welcome页,WelcomeController.java如下:
package com.gzframe.demo.mvc.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; @Controller
public class WelcomeController { @RequestMapping(value="/welcome",method=RequestMethod.GET)
public ModelAndView welcome(){
System.out.println("------------welcome");
ModelAndView mv = new ModelAndView();
mv.setViewName("welcome");
return mv;
} }
2.然后定义消息生产和消费的控制器,DemoController.java,代码如下
package com.gzframe.demo.mvc.controller; import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*; import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; import com.gzframe.demo.activemq.consumer.ConsumerService;
import com.gzframe.demo.activemq.producer.ProducerService; @Controller
public class DemoController { //队列名gzframe.demo
@Resource(name="demoQueueDestination")
private Destination demoQueueDestination; //队列消息生产者
@Resource(name="producerService")
private ProducerService producer; //队列消息消费者
@Resource(name="consumerService")
private ConsumerService consumer; @RequestMapping(value="/producer",method=RequestMethod.GET)
public ModelAndView producer(){
System.out.println("------------go producer"); Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format( now );
System.out.println(time); ModelAndView mv = new ModelAndView();
mv.addObject("time", time);
mv.setViewName("jms_producer");
return mv;
} @RequestMapping(value="/onsend",method=RequestMethod.POST)
public ModelAndView producer(@RequestParam("message") String message) {
System.out.println("------------send to jms");
ModelAndView mv = new ModelAndView();
producer.sendMessage(demoQueueDestination, message);
mv.setViewName("welcome");
return mv;
} @RequestMapping(value="/receive",method=RequestMethod.GET)
public ModelAndView queue_receive() throws JMSException {
System.out.println("------------receive message");
ModelAndView mv = new ModelAndView(); TextMessage tm = consumer.receive(demoQueueDestination);
mv.addObject("textMessage", tm.getText()); mv.setViewName("queue_receive");
return mv;
} /*
* ActiveMQ Manager Test
*/
@RequestMapping(value="/jms",method=RequestMethod.GET)
public ModelAndView jmsManager() throws IOException {
System.out.println("------------jms manager");
ModelAndView mv = new ModelAndView();
mv.setViewName("welcome"); JMXServiceURL url = new JMXServiceURL("");
JMXConnector connector = JMXConnectorFactory.connect(url);
connector.connect();
MBeanServerConnection connection = connector.getMBeanServerConnection(); return mv;
} }
五、效果展示
首先访问欢迎页,如下
然后点“去发消息”,进入到如下页面,默认消息框一已经填写了时间,点击提交,会将时间“2015-12-25 11:51:25”提交到qctivemq服务器中,
提交完成后,根据页面代码,会转到欢迎页,在欢迎页中既可以点击“从队列中取一个消息”,效果如下
可以看到,取到的消息即为刚才提交的时间,demo成功!
经过以上操作后的后台输出如下
六、加入监听器
以上例子中,接收消息是靠手动点击接收,下面将配置一个消息监听器“QueueMessageListener.java”,负责自动监听qctiveMQ中的队列消息,
一旦有新消息后,将自动读取消费,妈妈再也不用担心漏掉消息啦!
1.首先写一个监听的类“QueueMessageListener.java”,必须实现“MessageListerner”接口,代码如下
package com.gzframe.demo.activemq.listener; import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage; public class QueueMessageListener implements MessageListener { //当收到消息后,自动调用该方法
@Override
public void onMessage(Message message) { TextMessage tm = (TextMessage) message;
try {
System.out.println("QueueMessageListener监听到了文本消息:\t"
+ tm.getText());
//do something ...
} catch (JMSException e) {
e.printStackTrace();
}
} }
2.写完监听类后,打开activemq.xml配置文件,需要将这个监听配置到文件中,这样,应用加载后,即会加载此监听。
将以下的配置段加入到activemq.xml中
<!-- 配置消息队列监听者(Queue) -->
<bean id="queueMessageListener" class="com.gzframe.demo.activemq.listener.QueueMessageListener" /> <!-- 显示注入消息监听容器(Queue),配置连接工厂,监听的目标是demoQueueDestination,监听器是上面定义的监听器 -->
<bean id="queueListenerContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="demoQueueDestination" />
<property name="messageListener" ref="queueMessageListener" />
</bean>
3.测试
配置完成后,重新启动服务,去消息发送页提交消息,提交完毕后,监听检测到,将立即消费掉,并在后台打印出来
后台输出如下
spring与actionMQ整合的更多相关文章
- 轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)
轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)(国家级奖项获奖作品升级版,四版累计印刷27次发行量超10万册的轻量级Jav ...
- Spring Security 3整合CAS 实现SSO
spring security 3整合cas client用于实现各Application之间的单点登录. 1. 需要准备的jar spring-security-core-3.0.8.RELEASE ...
- 1.springMVC+spring+Mybatis的整合思路
SSM整合的过程:就是把一些东西交给spring管理,也就是添加配置文件的一个过程.那么有哪些东西我们要交给spring管理呢?大概有以下几个: 1.数据源(可配置数据库连接池) 2.SqlSessi ...
- Spring+springmvc+Mybatis整合案例 annotation版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:annotation版 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version=&qu ...
- Spring+springmvc+Mybatis整合案例 xml配置版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:xml版(myeclipse) 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version ...
- Spring与Mybatis整合的MapperScannerConfigurer处理过程源码分析
前言 本文将分析mybatis与spring整合的MapperScannerConfigurer的底层原理,之前已经分析过java中实现动态,可以使用jdk自带api和cglib第三方库生成动态代理. ...
- Mybatis学习--spring和Mybatis整合
简介 在前面写测试代码的时候,不管是基于原始dao还是Mapper接口开发都有许多的重复代码,将spring和mybatis整合可以减少这个重复代码,通过spring的模板方法模式,将这些重复的代码进 ...
- Spring(八)SSH整合简述
一.Spring与Struts2的整合 1.1.整合步骤 1.2.配置web.xml 1.3.配置spring配置文件applicationContext.xml 1.4.配置struts配置文件 1 ...
- Spring学习6-Spring整合Struts2
一.Spring为什么要整合Struts2 Struts2与Spring进行整合的根本目的就是要让 Spring为Struts2的Action注入所需的资源对象,它们整合的原理则是只要导入了s ...
随机推荐
- 常用Linux网络命令
TCP状态统计: netstat -anp TCP各个状态的连接数:netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a] ...
- Android WebView设置背景透明
Adndroid 2.x的设置 在Android 2.x下,设置webview背景为透明的方法: wvContent.setBackgroundColor(0); Adndroid 4.0 由于硬件加 ...
- springboot读取本地项目文件
在读取springBoot+gradle构建的项目时,如果使用传统的FileInputStream读取文件流或者ResourceUtils工具类的方式 File file= ResourceUtils ...
- Windows下OSGEarth的编译过程
目录 1. 依赖 1) OpenSceneGraph 2) GDAL 3) CURL 4) GEOS 5) 其他 2. 编译 1) 设置参数 2) 配置路径 3) 生成编译 3. 参考文献 1. 依赖 ...
- 基于cxf开发的WebService
Node.jshttps://www.cnblogs.com/goldlong/p/8027997.htmlQQ音乐apihttps://juejin.im/post/5a35228e51882506 ...
- 每天学点node系列-stream
在编写代码时,我们应该有一些方法将程序像连接水管一样连接起来 -- 当我们需要获取一些数据时,可以去通过"拧"其他的部分来达到目的.这也应该是IO应有的方式. -- Doug Mc ...
- 并发编程-concurrent指南-阻塞队列-数组阻塞队列ArrayBlockingQueue
ArrayBlockingQueue类是实现了BlockingQueue. ArrayBlockingQueue是一个有界的阻塞队列,其内部实现是将对象放在一个数组中. 放入元素方法: (1) add ...
- 基于C#的机器学习--旅行推销员问题
我们有一个必须在n个城市之间旅行的推销员.他不在乎什么顺序.他最先或最后访问的城市除外.他唯一关心的是他会去拜访每一个人,每个城市只有一次,最后一站是他得家. 每个城市都是一个节点,每个节点通过一条边 ...
- Git使用小技巧之回滚和撤销
想要获取更多文章可以访问我的博客 - 代码无止境. 日常的开发,我们难免会创建错误的git提交记录,整个时候git给我们提供了两个命令来解决这个问题.一个命令是git reset,另一个是git re ...
- websocket实现群聊和单聊(转)
昨日内容回顾 1.Flask路由 1.endpoint="user" # 反向url地址 2.url_address = url_for("user") 3.m ...