一.Pom文件
<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>ActiveMQ-Spring</groupId> <artifactId>ActiveMQ-Spring</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>ActiveMQ-Spring4 Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring-version>3.2.6.RELEASE</spring-version> <activemq-version>5.6.0</activemq-version> <jms-version>2.0</jms-version> </properties> <dependencies> <!--Junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> <!--Slf4j--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-version}</version> </dependency> <!--Spring.Jms--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>${spring-version}</version> </dependency> <!--Javax.Jms--> <dependency> <groupId>javax.jms</groupId> <artifactId>javax.jms-api</artifactId> <version>${jms-version}</version> </dependency> <!--ActiveMQ--> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-all</artifactId> <version>${activemq-version}</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> <version>${activemq-version}</version> </dependency> <!--xbean-spring--> <dependency> <groupId>org.apache.xbean</groupId> <artifactId>xbean-spring</artifactId> <version>3.16</version> </dependency> </dependencies> <build> <finalName>ActiveMQ-Spring</finalName> </build> </project>
二.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" 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.xsd"> <context:annotation-config/> <context:component-scan base-package="com.guangjieba.whale.reptile.**"/> <!--配置ActionMQ的连接工厂,用amq配置--> <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"> <property name="brokerURL" value="tcp://localhost:61616"/> </bean> <!--<amq:connectionFactory id="connectionFactory" brokerURL="tcp://localhost:61616"/>--> <!--配置Queue消息目的地,用amq配置--> <bean id="quartzQueue" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="QuartzQueue"/> <!--<constructor-arg index="0" value="QuartzQueue"/>--> <!--带index参数--> </bean> <bean id="realTimeQueue" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="RealTimeQueue"/> </bean> <!--<amq:queue id="queue" physicalName="FirstQueue"/>--> <!--配置Topic消息目的地--> <!--<bean id="topic" class="org.apache.activemq.command.ActiveMQTopic"> <constructor-arg index="0" value="MyTopic"/> </bean>--> <!--配置JmsTemplate:手动,有超时时间--> <bean id="jmsTemplate1" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory" ref="connectionFactory"/> <property name="defaultDestination" ref="quartzQueue"/> <property name="receiveTimeout" value="2000" /> </bean> <!--配置JmsTemplate:即时——通过监听器实现--> <bean id="jmsTemplate2" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory" ref="connectionFactory" /> <property name="defaultDestination" ref="realTimeQueue" /> </bean> <!--配置消息监听(方式一),消息入队通知接收器,即时出队--> <bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"> <property name="concurrentConsumers" value="10" /> <property name="connectionFactory" ref="connectionFactory" /> <property name="destinationName" value="RealTimeQueue" /> <property name="messageListener" ref="realTimeActiveMQ" /> <!--被监听的类--> <property name="pubSubNoLocal" value="false"/> </bean> <!--配置消息监听(方式二),消息入队通知接收器,即时出队--> <jms:listener-container connection-factory="connectionFactory"> <jms:listener destination="RealTimeQueue" ref="realTimeActiveMQ"/> <!--<jms:listener destination="RealTimeQueue" ref="realTimeActiveMQ" method="receive"/>--> </jms:listener-container> </beans>
三.ActiveMQ类1:手动型
import com.huaxia.entity.Goods
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.jms.*;
/**
* Created with IntelliJ IDEA..
* User: Leon
* Date: 14-2-28
* Time: 下午4:52
* To change this template use File | Settings | File Templates.
*/
@Service
public class QuartzActiveMQ {
/*注:因为配置文件中有两个JmsTemplate,故用@Resource,可byName注入*/
@Resource
private JmsTemplate jmsTemplate1;
/**
* 直接将消息转化并入队
* @param rbGoods 发送的商品对象
*/
public void simpleSend(final Goods goods) {
jmsTemplate1.convertAndSend(goods);
}
/**
* 发送消息到队列中
* @param rbGoods 发送的商品对象
*/
public void send(final Goods goods) {
jmsTemplate1.send(new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createObjectMessage(goods);
}
});
}
/**
* 从队列中接收消息并返回(手动方式)
*/
public Goods receive() {
ObjectMessage message = (ObjectMessage) jmsTemplate1.receive();
if (message == null) {
return null;
}
try {
Goods goods = (Goods) message.getObject();
return goods;
} catch (JMSException e) {
e.printStackTrace();
}
return null;
}
四.ActiveMQ类2:即时通信型
import com.huaxia.entity.Goods;
import com.huaxia.dao.GoodsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
/**
* Created with IntelliJ IDEA..
* User: Leon
* Date: 14-3-1
* Time: 上午10:10
* To change this template use File | Settings | File Templates.
* 通过监听器实时监听并接收消息
*/
@Service
public class RealTimeActiveMQ implements MessageListener {
@Resource
private JmsTemplate jmsTemplate2;
@Autowired
private GoodsRepository roodsRepository;
/**
* 商品入队
* @param rbGoods 商品
*/
public void send(final Goods goods){
jmsTemplate2.convertAndSend(goods);
}
/**
* 商品即时出队并持久化
* @param message
*/
@Override
public void onMessage(Message message) {
if (message instanceof ObjectMessage) {
try {
Goods goods = (Goods) ((ObjectMessage) message).getObject();
Goods roodsTemp = goodsRepository.save(goods);
if (goodsTemp.getId() == null) {
send(goods);
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
五.接口
@Controller
@RequestMapping("/brandsource")
public class BrandSourceController {
@Autowired
private QuartzActiveMQ activeMQController;、
@Autowired
private IGoodsRestTemplate iGoodsRestTemplate;
@RequestMapping(value = "/goods/check", method = RequestMethod.GET)
private void checkGoods() {
while (true) {
int count = 0;
RbGoods rbGoods = activeMQController.receive();
if (rbGoods != null) {
boolean flag = iGoodsRestTemplate.postUpdateGoodsStatus(rbGoods);
while (!flag) {
count += 1;
if (count == 3) {
activeMQController.send(rbGoods);
break;
}
flag = iGoodsRestTemplate.postUpdateGoodsStatus(rbGoods);
}
continue;
}
else {
break;
}
}
}
}
六.测试类1:手动型
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Created with IntelliJ IDEA..
* User: Leon
* Date: 14-2-28
* Time: 下午3:37
* To change this template use File | Settings | File Templates.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"/ServletContext.xml"})
public class QuartzActiveMQTest {
@Autowired
private QuartzActiveMQ activeMQController;
@Autowired
private RbGoodsRepository rbGoodsRepository;
@Autowired
WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void init() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
/**
* 往队列里添加数据
*/
@Test
public void sendTest() {
RbGoods rbGoods = rbGoodsRepository.findOne(QRbGoods.rbGoods.id.eq("aHR0cDovL3d3dy5obS5jb20vY24vcHJvZHVjdC8wODcwOT9hcnRpY2xlPTA4NzA5LUM"));
System.out.println(rbGoods);
/*RbGoods rbGoods = new RbGoods();
rbGoods.setBrandId("123234");
rbGoods.setBrandName("sdaf");*/
activeMQController.send(rbGoods);
}
/**
* 批量审核对接接口的测试
*/
@Test
public void checkGoodsTest() {
try {
mockMvc.perform(get("/brandsource/goods/check").accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从队列里面拿出数据
*/
@Test
public void receiveTest() {
activeMQController.receive();
}
}
七.测试类2:即时通信型
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* Created with IntelliJ IDEA..
* User: Leon
* Date: 14-3-1
* Time: 上午10:25
* To change this template use File | Settings | File Templates.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"/ServletContext.xml"})
public class RealTimeActiveMQTest {
@Autowired
private RealTimeActiveMQ realTimeActiveMQ;
@Autowired
private RbGoodsRepository rbGoodsRepository;
@Autowired
WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void init() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void sendTest() {
realTimeActiveMQ.send(new RbGoods());
}
}
八.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="2.5">
<display-name>Weibo Web Application</display-name>
<filter>
<filter-name>CORS Filter</filter-name>
<filter-class>org.ebaysf.web.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>encodingFilter</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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>-->
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>com.guangjieba.whale.reptile.application.InitApp</listener-class>
</listener>
<!-- Disables Servlet Container welcome file handling. Needed for compatibility with Servlet 3.0 and Tomcat 7.0 -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>