下面开始玩玩activeMQ和spring的整合,本人比较懒,直接拿上次搭建好的Springmvc+mybatis的项目,在这基础上进行整合上activeMQ
我们只讲重点代码,源码下载
整个项目的文件结构如下:
1、修改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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cwh.activeMQ</groupId>
<artifactId>activeMQ</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<junit.version>4.10</junit.version>
<spring-test.version>3.2.8.RELEASE</spring-test.version>
<mysql.version>5.1.22</mysql.version>
<spring-core.version>3.2.8.RELEASE</spring-core.version>
<spring-context.version>3.2.8.RELEASE</spring-context.version>
<spring-tx.version>3.2.8.RELEASE</spring-tx.version>
<spring-jdbc.version>3.2.8.RELEASE</spring-jdbc.version>
<spring-webmvc.version>3.2.8.RELEASE</spring-webmvc.version>
<mybatis.version>3.2.7</mybatis.version>
<mybatis-spring.version>1.2.2</mybatis-spring.version>
<aspectjweaver.version>1.8.1</aspectjweaver.version>
<jackson-core-asl.version>1.9.2</jackson-core-asl.version>
<jackson-mapper-asl.version>1.9.2</jackson-mapper-asl.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<log4j.version>1.2.16</log4j.version>
<commons-dbcp.version>1.2.1</commons-dbcp.version>
<fastjson.version>1.1.37</fastjson.version>
<jstl.version>1.1.0</jstl.version>
<standard.version>1.1.0</standard.version>
<commons-configuration.version>1.6</commons-configuration.version>
<commons-fileupload.version>1.2.1</commons-fileupload.version>
</properties>
<!-- <dependencyManagement> -->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-test.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-core.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-context.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-tx.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-jdbc.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-webmvc.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${jackson-core-asl.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson-mapper-asl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons-dbcp.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${standard.version}</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>${commons-configuration.version}</version>
</dependency>
<!-- 以下是activeMQ所需的包 -->
<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.9.0</version>
</dependency>
</dependencies>
<!-- </dependencyManagement> -->
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<version>3.0</version>
</configuration>
</plugin>
</plugins>
</build>
</project>
说明:里面包括了mybatis整合相关的包
2、新建producerService
在com.cwh.activeMQ.producer下创建producerService类:
package com.cwh.activeMQ.producer;
import java.io.Serializable;
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("Send " + msg + " to Destination " + destination.toString());
MessageCreator messageCreator = new MessageCreator(){
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(msg);
}
};
jmsTemplate.send(destination, messageCreator);
}
public void sendMessage(Destination destination,final Serializable msg){
MessageCreator messageCreator = new MessageCreator(){
public Message createMessage(Session session) throws JMSException {
return session.createObjectMessage(msg);
}
};
jmsTemplate.send(destination, messageCreator);
}
public void sendMessage(final String msg){
String destination = jmsTemplate.getDefaultDestinationName().toString();
System.out.println("Send " + msg + " to Destination " + destination);
MessageCreator messageCreator = new MessageCreator(){
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(msg);
}
};
jmsTemplate.send(messageCreator);
}
}
3、新建consumerService
在com.cwh.activeMQ.consumer包下新建consumerService类:
package com.cwh.activeMQ.consumer;
import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.ObjectMessage;
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);
return tm;
}
public ObjectMessage receiveObject(Destination destination) {
ObjectMessage tm = (ObjectMessage) jmsTemplate.receive(destination);
return tm;
}
}
4.新建activemqcontroller类
在com.cwh.controller包下创建ActiveMQController.java
package com.cwh.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
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.beans.factory.annotation.Autowired;
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.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.cwh.activeMQ.consumer.ConsumerService;
import com.cwh.activeMQ.producer.ProducerService;
@Controller
@RequestMapping("activeMQ")
public class ActiveMQController {
@Resource(name = "demoQueueDestination")
private Destination demoQueueDestination;
@Resource(name = "producerService")
private ProducerService producer;
@Resource(name = "consumerService")
private ConsumerService consumer;
@RequestMapping(value = "/main", method = RequestMethod.GET)
public String init(){
return "activeMQ_main";
}
/**
* 发布信息到queue
* @param message
* @return
*/
@RequestMapping(value = "/onsend", method = RequestMethod.POST)
public String producer(@RequestParam("message") String message) {
System.out.println("发布:"+message);
producer.sendMessage(demoQueueDestination, message);
return "activeMQ_receive";
}
/**
* 消费信息
* @param mv
* @return
* @throws JMSException
*/
@RequestMapping(value = "/receive", method = RequestMethod.GET)
public @ResponseBody Map<String,Object> queue_receive(ModelAndView mv) throws JMSException {
TextMessage tm = consumer.receive(demoQueueDestination);
System.out.println("消费信息:"+tm.getText());
Map<String,Object>msg = new HashMap<String,Object>();
if (tm == null) {
msg.put("textMessage", "Queue is Empty");
} else {
msg.put("textMessage", tm.getText());
}
return msg;
}
}
5、新建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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.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.cwh.activeMQ" />
<mvc:annotation-driven />
<amq:connectionFactory id="amqConnectionFactory"
brokerURL="tcp://127.0.0.1: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>activeMQ+spring</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>
<bean id="producerService" class="com.cwh.activeMQ.producer.ProducerService">
</bean>
<bean id="consumerService" class="com.cwh.activeMQ.consumer.ConsumerService">
</bean>
</beans>
6、applicationContext.xml
这里面包括了mybatis的东西,可以忽略不要
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<context:annotation-config/>
<context:component-scan base-package="com.cwh.*"/>
<!-- <tx:annotation-driven proxy-target-class="true"/> -->
<context:property-placeholder location="classpath:*.properties"/><!-- 加载配置文件 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource属性指定要用到的连接池-->
<property name="dataSource" ref="dataSource"/>
<!--configLocation属性指定mybatis的核心配置文件-->
<!-- <property name="configLocation" value="/com/cwh/config/Configuration.xml" /> -->
<!-- 所有配置的mapper文件 -->
<property name="mapperLocations" value="classpath*:com/cwh/mapper/*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.cwh.inter" />
</bean>
</beans>
7、spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.cwh.controller" />
<mvc:annotation-driven />
<mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
<mvc:default-servlet-handler/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
8、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_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:com/cwh/config/applicationContext.xml;classpath*:com/cwh/config/*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</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*:com/cwh/config/spring-mvc.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>
</web-app>
9、新建activeMQ_main.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<c:set var="ctxPath" value="<%=basePath%>" scope="request"/>
<!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>
<form action="${ctxPath }activeMQ/onsend" method="post">
MessageText:<textarea name="message">${time}</textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>
10、新建activeMQ_receive.jsp
<%@ page language="java" import="java.util.*" pageEncoding="Utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<c:set var="ctxPath" value="<%=basePath%>" scope="request"/>
<!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>
<a href="${ctxPath }activeMQ/receive">消费信息</a>
</body>
</html>
ok!这样就欧了
11、tomcat部署项目
访问http://localhost:8080/activeMQ/activeMQ/main
输入信息:helloworld提交发布信息
接着我们访问消费者消费信息:
我们可以看到消费者已经拿到了信息“helloworld”
12、至此我们activeMQ+spring也就整合完毕