Sping整合ActiveMQ(四.实例详解)

Sping整合ActiveMQ(四.实例详解)

    博客分类: 
  • ActiveMQ
  • Spring
Java Jms Spring ActiveMQ 

一.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.   
  4.   <modelVersion>4.0.0</modelVersion>  
  5.   
  6.   <groupId>ActiveMQ-Spring</groupId>  
  7.   <artifactId>ActiveMQ-Spring</artifactId>  
  8.   <packaging>war</packaging>  
  9.   <version>1.0-SNAPSHOT</version>  
  10.   
  11.   <name>ActiveMQ-Spring4 Maven Webapp</name>  
  12.   <url>http://maven.apache.org</url>  
  13.   
  14.     <properties>  
  15.         <spring-version>3.2.6.RELEASE</spring-version>  
  16.         <activemq-version>5.6.0</activemq-version>  
  17.         <jms-version>2.0</jms-version>  
  18.     </properties>  
  19.   
  20.     <dependencies>  
  21.         <!--Junit-->  
  22.         <dependency>  
  23.             <groupId>junit</groupId>  
  24.             <artifactId>junit</artifactId>  
  25.             <version>4.10</version>  
  26.         </dependency>  
  27.         <!--Slf4j-->  
  28.         <dependency>  
  29.             <groupId>org.slf4j</groupId>  
  30.             <artifactId>slf4j-api</artifactId>  
  31.             <version>1.7.5</version>  
  32.         </dependency>  
  33.         <!--Spring-->  
  34.         <dependency>  
  35.             <groupId>org.springframework</groupId>  
  36.             <artifactId>spring-core</artifactId>  
  37.             <version>${spring-version}</version>  
  38.         </dependency>  
  39.         <dependency>  
  40.             <groupId>org.springframework</groupId>  
  41.             <artifactId>spring-context</artifactId>  
  42.             <version>${spring-version}</version>  
  43.         </dependency>  
  44.         <dependency>  
  45.             <groupId>org.springframework</groupId>  
  46.             <artifactId>spring-context-support</artifactId>  
  47.             <version>${spring-version}</version>  
  48.         </dependency>  
  49.         <dependency>  
  50.             <groupId>org.springframework</groupId>  
  51.             <artifactId>spring-tx</artifactId>  
  52.             <version>${spring-version}</version>  
  53.         </dependency>  
  54.         <dependency>  
  55.             <groupId>org.springframework</groupId>  
  56.             <artifactId>spring-web</artifactId>  
  57.             <version>${spring-version}</version>  
  58.         </dependency>  
  59.         <dependency>  
  60.             <groupId>org.springframework</groupId>  
  61.             <artifactId>spring-webmvc</artifactId>  
  62.             <version>${spring-version}</version>  
  63.         </dependency>  
  64.         <dependency>  
  65.             <groupId>org.springframework</groupId>  
  66.             <artifactId>spring-test</artifactId>  
  67.             <version>${spring-version}</version>  
  68.         </dependency>  
  69.         <!--Spring.Jms-->  
  70.         <dependency>  
  71.             <groupId>org.springframework</groupId>  
  72.             <artifactId>spring-jms</artifactId>  
  73.             <version>${spring-version}</version>  
  74.         </dependency>  
  75.         <!--Javax.Jms-->  
  76.         <dependency>  
  77.             <groupId>javax.jms</groupId>  
  78.             <artifactId>javax.jms-api</artifactId>  
  79.             <version>${jms-version}</version>  
  80.         </dependency>  
  81.         <!--ActiveMQ-->  
  82.         <dependency>  
  83.             <groupId>org.apache.activemq</groupId>  
  84.             <artifactId>activemq-all</artifactId>  
  85.             <version>${activemq-version}</version>  
  86.         </dependency>  
  87.         <dependency>  
  88.             <groupId>org.apache.activemq</groupId>  
  89.             <artifactId>activemq-pool</artifactId>  
  90.             <version>${activemq-version}</version>  
  91.         </dependency>  
  92.         <!--xbean-spring-->  
  93.         <dependency>  
  94.             <groupId>org.apache.xbean</groupId>  
  95.             <artifactId>xbean-spring</artifactId>  
  96.             <version>3.16</version>  
  97.         </dependency>  
  98.   
  99.     </dependencies>  
  100.   
  101.   <build>  
  102.     <finalName>ActiveMQ-Spring</finalName>  
  103.   </build>  
  104.   
  105. </project>  

 

二.Spring配置文件

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.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.          http://www.springframework.org/schema/context  
  8.          http://www.springframework.org/schema/context/spring-context.xsd">  
  9.   
  10.     <context:annotation-config/>  
  11.     <context:component-scan base-package="com.guangjieba.whale.reptile.**"/>  
  12.   
  13.     <!--配置ActionMQ的连接工厂,用amq配置-->  
  14.     <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
  15.         <property name="brokerURL" value="tcp://localhost:61616"/>  
  16.     </bean>  
  17.     <!--<amq:connectionFactory id="connectionFactory" brokerURL="tcp://localhost:61616"/>-->  
  18.   
  19.     <!--配置Queue消息目的地,用amq配置-->  
  20.     <bean id="quartzQueue" class="org.apache.activemq.command.ActiveMQQueue">  
  21.         <constructor-arg value="QuartzQueue"/>  
  22.         <!--<constructor-arg index="0" value="QuartzQueue"/>-->  <!--带index参数-->  
  23.     </bean>  
  24.     <bean id="realTimeQueue" class="org.apache.activemq.command.ActiveMQQueue">  
  25.         <constructor-arg value="RealTimeQueue"/>  
  26.     </bean>  
  27.     <!--<amq:queue id="queue" physicalName="FirstQueue"/>-->  
  28.   
  29.     <!--配置Topic消息目的地-->  
  30.     <!--<bean id="topic" class="org.apache.activemq.command.ActiveMQTopic">  
  31.         <constructor-arg index="0" value="MyTopic"/>  
  32.     </bean>-->  
  33.   
  34.     <!--配置JmsTemplate:手动,有超时时间-->  
  35.     <bean id="jmsTemplate1" class="org.springframework.jms.core.JmsTemplate">  
  36.         <property name="connectionFactory" ref="connectionFactory"/>  
  37.         <property name="defaultDestination" ref="quartzQueue"/>  
  38.         <property name="receiveTimeout" value="2000" />  
  39.     </bean>  
  40.     <!--配置JmsTemplate:即时——通过监听器实现-->  
  41.     <bean id="jmsTemplate2" class="org.springframework.jms.core.JmsTemplate">  
  42.         <property name="connectionFactory" ref="connectionFactory" />  
  43.         <property name="defaultDestination" ref="realTimeQueue" />  
  44.     </bean>  
  45.   
  46.     <!--配置消息监听(方式一),消息入队通知接收器,即时出队-->  
  47.     <bean id="listenerContainer"  
  48.           class="org.springframework.jms.listener.DefaultMessageListenerContainer">  
  49.         <property name="concurrentConsumers" value="10" />  
  50.         <property name="connectionFactory" ref="connectionFactory" />  
  51.         <property name="destinationName" value="RealTimeQueue" />      
  52.         <property name="messageListener" ref="realTimeActiveMQ" />   <!--被监听的类-->  
  53.         <property name="pubSubNoLocal" value="false"/>  
  54.     </bean>  
  55.   
  56.     <!--配置消息监听(方式二),消息入队通知接收器,即时出队-->  
  57.     <jms:listener-container connection-factory="connectionFactory">  
  58.         <jms:listener destination="RealTimeQueue" ref="realTimeActiveMQ"/>  
  59.         <!--<jms:listener destination="RealTimeQueue" ref="realTimeActiveMQ" method="receive"/>-->  
  60.     </jms:listener-container>  
  61. </beans>  
 

 三.ActiveMQ类1:手动型

Java代码   收藏代码
  1. import com.huaxia.entity.Goods  
  2. import org.springframework.jms.core.JmsTemplate;  
  3. import org.springframework.jms.core.MessageCreator;  
  4. import org.springframework.stereotype.Service;  
  5.   
  6. import javax.annotation.Resource;  
  7. import javax.jms.*;  
  8.   
  9. /** 
  10.  * Created with IntelliJ IDEA.. 
  11.  * User: Leon 
  12.  * Date: 14-2-28 
  13.  * Time: 下午4:52 
  14.  * To change this template use File | Settings | File Templates. 
  15.  */  
  16. @Service  
  17. public class QuartzActiveMQ {  
  18.   
  19.     /*注:因为配置文件中有两个JmsTemplate,故用@Resource,可byName注入*/  
  20.     @Resource  
  21.     private JmsTemplate jmsTemplate1;  
  22.   
  23.     /** 
  24.      * 直接将消息转化并入队 
  25.      * @param rbGoods 发送的商品对象 
  26.      */  
  27.     public void simpleSend(final Goods goods) {  
  28.         jmsTemplate1.convertAndSend(goods);  
  29.     }  
  30.   
  31.     /** 
  32.      * 发送消息到队列中 
  33.      * @param rbGoods 发送的商品对象 
  34.      */  
  35.     public void send(final Goods goods) {  
  36.         jmsTemplate1.send(new MessageCreator() {  
  37.             @Override  
  38.             public Message createMessage(Session session) throws JMSException {  
  39.                 return session.createObjectMessage(goods);  
  40.             }  
  41.         });  
  42.     }  
  43.   
  44.     /** 
  45.      * 从队列中接收消息并返回(手动方式) 
  46.      */  
  47.     public Goods receive() {  
  48.         ObjectMessage message = (ObjectMessage) jmsTemplate1.receive();  
  49.         if (message == null) {  
  50.             return null;  
  51.         }  
  52.         try {  
  53.             Goods goods = (Goods) message.getObject();  
  54.             return goods;  
  55.         } catch (JMSException e) {  
  56.             e.printStackTrace();  
  57.         }  
  58.         return null;  
  59.     }  

 

 四.ActiveMQ类2:即时通信型

Java代码   收藏代码
  1. import com.huaxia.entity.Goods;  
  2. import com.huaxia.dao.GoodsRepository;  
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.jms.core.JmsTemplate;  
  5. import org.springframework.stereotype.Service;  
  6.   
  7. import javax.annotation.Resource;  
  8. import javax.jms.JMSException;  
  9. import javax.jms.Message;  
  10. import javax.jms.MessageListener;  
  11. import javax.jms.ObjectMessage;  
  12.   
  13. /** 
  14.  * Created with IntelliJ IDEA.. 
  15.  * User: Leon 
  16.  * Date: 14-3-1 
  17.  * Time: 上午10:10 
  18.  * To change this template use File | Settings | File Templates. 
  19.  * 通过监听器实时监听并接收消息 
  20.  */  
  21. @Service  
  22. public class RealTimeActiveMQ implements MessageListener {  
  23.   
  24.     @Resource  
  25.     private JmsTemplate jmsTemplate2;  
  26.     @Autowired  
  27.     private GoodsRepository roodsRepository;  
  28.   
  29.     /** 
  30.      * 商品入队 
  31.      * @param rbGoods 商品 
  32.      */  
  33.     public void send(final Goods goods){  
  34.         jmsTemplate2.convertAndSend(goods);  
  35.     }  
  36.   
  37.     /** 
  38.      * 商品即时出队并持久化 
  39.      * @param message 
  40.      */  
  41.     @Override  
  42.     public void onMessage(Message message) {  
  43.         if (message instanceof ObjectMessage) {  
  44.             try {  
  45.                 Goods goods = (Goods) ((ObjectMessage) message).getObject();  
  46.                 Goods roodsTemp = goodsRepository.save(goods);  
  47.                 if (goodsTemp.getId() == null) {  
  48.                     send(goods);  
  49.                 }  
  50.             } catch (JMSException e) {  
  51.                 e.printStackTrace();  
  52.             }  
  53.         }  
  54.     }  

 

 .接口

 

Java代码   收藏代码
  1. @Controller  
  2. @RequestMapping("/brandsource")  
  3. public class BrandSourceController {  
  4.   
  5.     @Autowired  
  6.     private QuartzActiveMQ activeMQController;、  
  7.     @Autowired  
  8.     private IGoodsRestTemplate iGoodsRestTemplate;  
  9.    
  10.     @RequestMapping(value = "/goods/check", method = RequestMethod.GET)  
  11.     private void checkGoods() {  
  12.         while (true) {  
  13.             int count = 0;  
  14.             RbGoods rbGoods = activeMQController.receive();  
  15.             if (rbGoods != null) {  
  16.                 boolean flag = iGoodsRestTemplate.postUpdateGoodsStatus(rbGoods);  
  17.                 while (!flag) {  
  18.                     count += 1;  
  19.                     if (count == 3) {  
  20.                         activeMQController.send(rbGoods);  
  21.                         break;  
  22.                     }  
  23.                     flag = iGoodsRestTemplate.postUpdateGoodsStatus(rbGoods);  
  24.                 }  
  25.                 continue;  
  26.             }  
  27.             else {  
  28.                 break;  
  29.             }  
  30.         }  
  31.     }  
  32.   
  33. }  

 

 

 .测试类1:手动型

 

Java代码   收藏代码
  1. import org.junit.Before;  
  2. import org.junit.Test;  
  3. import org.junit.runner.RunWith;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.http.MediaType;  
  6. import org.springframework.test.context.ContextConfiguration;  
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  8. import org.springframework.test.context.web.WebAppConfiguration;  
  9. import org.springframework.test.web.servlet.MockMvc;  
  10. import org.springframework.test.web.servlet.setup.MockMvcBuilders;  
  11. import org.springframework.web.context.WebApplicationContext;  
  12.   
  13. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;  
  14. import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;  
  15. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;  
  16.   
  17.   
  18. /** 
  19.  * Created with IntelliJ IDEA.. 
  20.  * User: Leon 
  21.  * Date: 14-2-28 
  22.  * Time: 下午3:37 
  23.  * To change this template use File | Settings | File Templates. 
  24.  */  
  25. @RunWith(SpringJUnit4ClassRunner.class)  
  26. @WebAppConfiguration  
  27. @ContextConfiguration({"/ServletContext.xml"})  
  28. public class QuartzActiveMQTest {  
  29.   
  30.     @Autowired  
  31.     private QuartzActiveMQ activeMQController;  
  32.     @Autowired  
  33.     private RbGoodsRepository rbGoodsRepository;  
  34.     @Autowired  
  35.     WebApplicationContext webApplicationContext;  
  36.     private MockMvc mockMvc;  
  37.   
  38.     @Before  
  39.     public void init() {  
  40.         mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();  
  41.     }  
  42.   
  43.     /** 
  44.      * 往队列里添加数据 
  45.      */  
  46.     @Test  
  47.     public void sendTest() {  
  48.         RbGoods rbGoods = rbGoodsRepository.findOne(QRbGoods.rbGoods.id.eq("aHR0cDovL3d3dy5obS5jb20vY24vcHJvZHVjdC8wODcwOT9hcnRpY2xlPTA4NzA5LUM"));  
  49.         System.out.println(rbGoods);  
  50.         /*RbGoods rbGoods = new RbGoods(); 
  51.         rbGoods.setBrandId("123234"); 
  52.         rbGoods.setBrandName("sdaf");*/  
  53.         activeMQController.send(rbGoods);  
  54.     }  
  55.   
  56.     /** 
  57.      * 批量审核对接接口的测试 
  58.      */  
  59.     @Test  
  60.     public void checkGoodsTest() {  
  61.         try {  
  62.             mockMvc.perform(get("/brandsource/goods/check").accept(MediaType.APPLICATION_JSON))  
  63.                     .andDo(print())  
  64.                     .andExpect(status().isOk())  
  65.                     .andReturn();  
  66.         } catch (Exception e) {  
  67.             e.printStackTrace();  
  68.         }  
  69.     }  
  70.   
  71.     /** 
  72.      * 从队列里面拿出数据 
  73.      */  
  74.     @Test  
  75.     public void receiveTest() {  
  76.         activeMQController.receive();  
  77.     }  
  78. }  

 

 .测试类2:即时通信型

 

Java代码   收藏代码
  1. import org.junit.Before;  
  2. import org.junit.Test;  
  3. import org.junit.runner.RunWith;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.test.context.ContextConfiguration;  
  6. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  7. import org.springframework.test.context.web.WebAppConfiguration;  
  8. import org.springframework.test.web.servlet.MockMvc;  
  9. import org.springframework.test.web.servlet.setup.MockMvcBuilders;  
  10. import org.springframework.web.context.WebApplicationContext;  
  11.   
  12. /** 
  13.  * Created with IntelliJ IDEA.. 
  14.  * User: Leon 
  15.  * Date: 14-3-1 
  16.  * Time: 上午10:25 
  17.  * To change this template use File | Settings | File Templates. 
  18.  */  
  19. @RunWith(SpringJUnit4ClassRunner.class)  
  20. @WebAppConfiguration  
  21. @ContextConfiguration({"/ServletContext.xml"})  
  22. public class RealTimeActiveMQTest {  
  23.     @Autowired  
  24.     private RealTimeActiveMQ realTimeActiveMQ;  
  25.     @Autowired  
  26.     private RbGoodsRepository rbGoodsRepository;  
  27.     @Autowired  
  28.     WebApplicationContext webApplicationContext;  
  29.     private MockMvc mockMvc;  
  30.   
  31.     @Before  
  32.     public void init() {  
  33.         mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();  
  34.     }  
  35.   
  36.     @Test  
  37.     public void sendTest() {  
  38.         realTimeActiveMQ.send(new RbGoods());  
  39.     }  
  40. }  

 

 八.Web.xml配置文件

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns="http://java.sun.com/xml/ns/javaee"  
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  5.          version="2.5">  
  6.   
  7.     <display-name>Weibo Web Application</display-name>  
  8.   
  9.     <filter>  
  10.         <filter-name>CORS Filter</filter-name>  
  11.         <filter-class>org.ebaysf.web.cors.CORSFilter</filter-class>  
  12.     </filter>  
  13.     <filter-mapping>  
  14.         <filter-name>CORS Filter</filter-name>  
  15.         <url-pattern>/*</url-pattern>  
  16.     </filter-mapping>  
  17.   
  18.     <filter>  
  19.         <filter-name>encodingFilter</filter-name>  
  20.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  21.         <init-param>  
  22.             <param-name>encoding</param-name>  
  23.             <param-value>UTF-8</param-value>  
  24.         </init-param>  
  25.     </filter>  
  26.   
  27.     <filter-mapping>  
  28.         <filter-name>encodingFilter</filter-name>  
  29.         <url-pattern>/*</url-pattern>  
  30.     </filter-mapping>  
  31.   
  32.     <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->  
  33.     <context-param>  
  34.         <param-name>contextConfigLocation</param-name>  
  35.         <param-value>/WEB-INF/spring/root-context.xml</param-value>  
  36.     </context-param>  
  37.   
  38.     <!-- Processes application requests -->  
  39.     <servlet>  
  40.         <servlet-name>appServlet</servlet-name>  
  41.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  42.         <init-param>  
  43.             <param-name>contextConfigLocation</param-name>  
  44.             <!--<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>-->  
  45.             <param-value>/WEB-INF/spring/root-context.xml</param-value>  
  46.         </init-param>  
  47.         <load-on-startup>1</load-on-startup>  
  48.     </servlet>  
  49.   
  50.     <servlet-mapping>  
  51.         <servlet-name>appServlet</servlet-name>  
  52.         <url-pattern>/</url-pattern>  
  53.     </servlet-mapping>  
  54.   
  55.     <!-- Creates the Spring Container shared by all Servlets and Filters -->  
  56.     <listener>  
  57.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  58.     </listener>  
  59.     <listener>  
  60.         <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
  61.     </listener>  
  62.     <listener>  
  63.         <listener-class>com.guangjieba.whale.reptile.application.InitApp</listener-class>  
  64.     </listener>  
  65.   
  66.     <!-- Disables Servlet Container welcome file handling. Needed for compatibility with Servlet 3.0 and Tomcat 7.0 -->  
  67.     <welcome-file-list>  
  68.         <welcome-file>index.html</welcome-file>  
  69.         <welcome-file>index.jsp</welcome-file>  
  70.     </welcome-file-list>  
  71.   
  72.   
  73. </web-app>  

 

你可能感兴趣的:(Sping整合ActiveMQ(四.实例详解))