activeMQ實例在項目中的運用【項目實戰系列】

1.下載ActiveMQ

去官方網站下載:http://activemq.apache.org/

2.運行ActiveMQ

解壓縮apache-activemq-5.14.0-bin.zip,然後雙擊apache-activemq-5.14.0\bin\activemq.bat運行ActiveMQ程序。

啓動ActiveMQ以後,登陸:http://localhost:8161/admin/ ,賬戶和密碼都是admin,然後可以自己添加一個Queue,這次項目

們通過代碼創建一個Queue.

好了,activeMQ就已經完成了部署,那麼怎麼把他運用到我們項目中呢,下面我就給大家介紹一下。

 

首先來看下我這個項目的整個目錄結構,總共分爲3個子項目,domain項目用於存放公共的實體類和工具類,打包成jar包供

其他2個包使用。Service項目則是activeMQ的提供者或者說是生產者,這裏主要是配置activeMQ的生成方式和創建Queue

那麼剩下來的client項目當然就是MQ的使用者或者說是消費者了,那邊產生消息,這邊消費消息。那我們來看看具體的代碼

吧。

首先介紹domain的項目,這個項目裏面主要定義了三種實體類,User.java Client.java News.java 只是用於測試而已,

那就隨便看其中一個就好了,User.java

[java] view plain copy
  1. package com.lwl.activemq.domain;  
  2.   
  3. import java.io.Serializable;  
  4. /** 
  5.  * 用戶測試類 
  6.  * @author Administrator 
  7.  * 
  8.  */  
  9. public class User implements Serializable{  
  10.   
  11.     private static final long serialVersionUID = 1L;  
  12.   
  13.     private long id;  
  14.       
  15.     private String username;  
  16.       
  17.     private String password;  
  18.       
  19.     private String sex;  
  20.       
  21.     private int age;  
  22.   
  23.     public long getId() {  
  24.         return id;  
  25.     }  
  26.   
  27.     public void setId(long id) {  
  28.         this.id = id;  
  29.     }  
  30.   
  31.     public String getUsername() {  
  32.         return username;  
  33.     }  
  34.   
  35.     public void setUsername(String username) {  
  36.         this.username = username;  
  37.     }  
  38.   
  39.     public String getPassword() {  
  40.         return password;  
  41.     }  
  42.   
  43.     public void setPassword(String password) {  
  44.         this.password = password;  
  45.     }  
  46.   
  47.     public String getSex() {  
  48.         return sex;  
  49.     }  
  50.   
  51.     public void setSex(String sex) {  
  52.         this.sex = sex;  
  53.     }  
  54.   
  55.     public int getAge() {  
  56.         return age;  
  57.     }  
  58.   
  59.     public void setAge(int age) {  
  60.         this.age = age;  
  61.     }  
  62.   
  63.     @Override  
  64.     public String toString() {  
  65.         return "User [id=" + id + ", username=" + username + ", password="  
  66.                 + password + ", sex=" + sex + ", age=" + age + "]";  
  67.     }  
  68. }  


domain項目添加好這3個實體類,就把這個項目通過maven打包成jar供其他2個項目使用即可。

那接下來我們來看下service項目的代碼結構吧

 

首先我們來看一下最主要的MQ的配置文件:

[html] view plain copy
  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" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:jms="http://www.springframework.org/schema/jms"  
  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-3.0.xsd    
  9.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  10.     http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd">  
  11.   
  12.     <!-- 這裏暴露內部統一使用的MQ地址 -->  
  13.     <bean id="internalTargetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
  14.         <property name="brokerURL" value="tcp://localhost:61616" />  
  15.     </bean>  
  16.     <bean id="internalConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory"  
  17.         destroy-method="stop">  
  18.         <property name="connectionFactory" ref="internalTargetConnectionFactory" />  
  19.         <property name="maxConnections" value="20" />  
  20.     </bean>  
  21.     <!-- Spring提供的JMS工具類,它可以進行消息發送、接收等 -->  
  22.     <bean id="internalJmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
  23.         <property name="connectionFactory" ref="internalConnectionFactory" />  
  24.     </bean>  
  25.   
  26.     <!-- 推送給用戶信息  創建一個Queue-->  
  27.     <bean id="userServiceQueue" class="org.apache.activemq.command.ActiveMQQueue">  
  28.         <constructor-arg>  
  29.             <value>user.service.queue</value>  
  30.         </constructor-arg>  
  31.     </bean>  
  32.     <!-- 推送給新聞信息   創建一個Queue-->  
  33.     <bean id="newsServiceQueue" class="org.apache.activemq.command.ActiveMQQueue">  
  34.         <constructor-arg>  
  35.             <value>news.service.queue</value>  
  36.         </constructor-arg>  
  37.     </bean>  
  38.     <!-- 推送給客戶信息   創建一個Queue-->  
  39.     <bean id="clientServiceQueue" class="org.apache.activemq.command.ActiveMQQueue">  
  40.         <constructor-arg>  
  41.             <value>client.service.queue</value>  
  42.         </constructor-arg>  
  43.     </bean>  
  44.   
  45.        
  46. </beans>  

那我們看下怎麼運用定義的這個配置文件呢?

首先我們定義一個通用的推送接口PushService.java

[java] view plain copy
  1. package com.lwl.activemq.service;  
  2.   
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5.   
  6. /** 
  7.  * 推送的接口 
  8.  * @author Administrator 
  9.  * @create 2016-8-10 下午3:41:03 
  10.  * @version 1.0 
  11.  */  
  12. public interface PushService {  
  13.   
  14.     public final ExecutorService pushExecutor = Executors.newFixedThreadPool(10);  
  15.       
  16.     public void push(Object info);  
  17.       
  18. }  


然後又實現了3中不同的推送內容:ClientPushServiceImpl.java  NewsPushServiceImpl.java  UserPushServiceImpl.java

就拿其中的一個來舉例,其他2個模式是一樣的

[java] view plain copy
  1. package com.lwl.activemq.service.impl;  
  2.   
  3. import javax.jms.Destination;  
  4. import javax.jms.JMSException;  
  5. import javax.jms.Message;  
  6. import javax.jms.Session;  
  7.   
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.beans.factory.annotation.Qualifier;  
  10. import org.springframework.stereotype.Service;  
  11. import org.springframework.jms.core.JmsTemplate;  
  12. import org.springframework.jms.core.MessageCreator;  
  13.   
  14. import com.alibaba.fastjson.JSON;  
  15. import com.lwl.activemq.domain.User;  
  16. import com.lwl.activemq.service.PushService;  
  17.   
  18.   
  19. @Service("userPushService")  
  20. public class UserPushServiceImpl implements PushService {  
  21.   
  22.       
  23.     @Autowired  
  24.     private JmsTemplate jmsTemplate;  
  25.       
  26.     /** 
  27.      * 這裏是根據MQ配置文件定義的queue來注入的,也就是這裏將會把不同的內容推送到不同的queue中 
  28.      */  
  29.     @Autowired  
  30.     @Qualifier("userServiceQueue")  
  31.     private Destination destination;  
  32.       
  33.     @Override  
  34.     public void push(final Object info) {  
  35.         pushExecutor.execute(new Runnable() {  
  36.             @Override  
  37.             public void run() {  
  38.                 jmsTemplate.send(destination, new MessageCreator() {  
  39.                     public Message createMessage(Session session) throws JMSException {  
  40.                          User p = (User) info;  
  41.                         return session.createTextMessage(JSON.toJSONString(p));  
  42.                     }  
  43.                 });  
  44.             }             
  45.         });  
  46.     }  
  47.   
  48. }  


接口也已經實現好了,剩下的就是看我們怎麼調用它了,那我們看看控制器吧:

[java] view plain copy
  1. package com.lwl.activemq.controller;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RequestMethod;  
  8. import org.springframework.web.bind.annotation.ResponseBody;  
  9.   
  10. import com.lwl.activemq.domain.Client;  
  11. import com.lwl.activemq.domain.News;  
  12. import com.lwl.activemq.domain.User;  
  13. import com.lwl.activemq.result.ResultRespone;  
  14. import com.lwl.activemq.service.PushService;  
  15.   
  16. @Controller  
  17. @RequestMapping("/push")  
  18. public class PushController {  
  19.   
  20.     @Resource(name="userPushService")  
  21.     private PushService userPushService;  
  22.       
  23.     @Resource(name="newsPushService")  
  24.     private PushService newsPushService;  
  25.       
  26.     @Resource(name="clientPushService")  
  27.     private PushService clientPushService;  
  28.       
  29.     /** 
  30.      * 用戶推送 
  31.      * @param info 
  32.      * @return 
  33.      * @author Administrator 
  34.      * @create 2016-8-10 下午4:22:28 
  35.      */  
  36.     @RequestMapping(value="/user",method=RequestMethod.POST)  
  37.     @ResponseBody  
  38.     public ResultRespone userPush(User info){  
  39.         ResultRespone respone = new ResultRespone();  
  40.         try {  
  41.             userPushService.push(info);  
  42.             respone.setData(info);  
  43.         } catch (Exception e) {  
  44.             e.printStackTrace();  
  45.             respone = new ResultRespone(false, e.getMessage());  
  46.         }  
  47.         return respone;  
  48.     }  
  49.       
  50.     /** 
  51.      * 新聞推送 
  52.      * @param info 
  53.      * @return 
  54.      * @author Administrator 
  55.      * @create 2016-8-10 下午4:22:38 
  56.      */  
  57.     @RequestMapping(value="/news",method=RequestMethod.POST)  
  58.     @ResponseBody  
  59.     public ResultRespone newsPush(News info){  
  60.         ResultRespone respone = new ResultRespone();  
  61.         try {  
  62.             newsPushService.push(info);  
  63.             respone.setData(info);  
  64.         } catch (Exception e) {  
  65.             e.printStackTrace();  
  66.             respone = new ResultRespone(false, e.getMessage());  
  67.         }  
  68.         return respone;  
  69.     }  
  70.     /** 
  71.      * 客戶推送 
  72.      * @param info 
  73.      * @return 
  74.      * @author Administrator 
  75.      * @create 2016-8-10 下午4:22:48 
  76.      */  
  77.     @RequestMapping(value="/client",method=RequestMethod.POST)  
  78.     @ResponseBody  
  79.     public ResultRespone clientPush(Client info){  
  80.         ResultRespone respone = new ResultRespone();  
  81.         try {  
  82.             clientPushService.push(info);  
  83.             respone.setData(info);  
  84.         } catch (Exception e) {  
  85.             e.printStackTrace();  
  86.             respone = new ResultRespone(false, e.getMessage());  
  87.         }  
  88.         return respone;  
  89.     }  
  90. }  

控制器也寫好了,剩下的就是前段頁面的調用了,那就快來看看吧index.html

[html] view plain copy
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html>  
  3.     <head>  
  4.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  5.         <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  6.         <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.           <script type="text/javascript" src="resources/jquery-1.9.1.js"></script>  
  8.      </head>     
  9. <body>  
  10. <br/><br/><br/>  
  11. 用戶姓名:<input type="text" id="username" />  
  12. 用戶密碼:<input type="text" id="password" />  
  13. 用戶性別:<input type="text" id="sex" />  
  14.  <input type="button" value="推送用戶信息" id="pushUser" />   
  15.    
  16. <br/><br/><br/>  
  17. 新聞標題:<input type="text" id="title" />  
  18. 新聞內容:<input type="text" id="content" />  
  19. 新聞路徑:<input type="text" id="url" />  
  20. 新聞作者:<input type="text" id="author" />  
  21.  <input type="button" value="推送新聞信息" id="pushNews" />   
  22.   
  23.   
  24. <br/><br/><br/>  
  25. 客戶姓名:<input type="text" id="name" />  
  26. 客戶地址:<input type="text" id="address" />  
  27. 客戶手機:<input type="text" id="mobile" />  
  28.  <input type="button" value="推送客戶信息" id="pushClient" />   
  29.   
  30.   
  31.   
  32.   
  33. <script type="text/javascript">  
  34.     $("#pushUser").click(function(){  
  35.         var data = {  
  36.                 username : $("#username").val(),  
  37.                 password : $("#password").val(),  
  38.                 sex      : $("#sex").val()  
  39.         };  
  40.         ajaxDo("/activemq-service/push/user",data);  
  41.     });  
  42.     $("#pushNews").click(function(){  
  43.         var data = {  
  44.                 title    : $("#title").val(),  
  45.                 content  : $("#content").val(),  
  46.                 author   : $("#author").val(),  
  47.                 url      : $("#url").val()  
  48.         };  
  49.         ajaxDo("/activemq-service/push/news",data);  
  50.     });  
  51.     $("#pushClient").click(function(){  
  52.         var data = {  
  53.                 name     : $("#name").val(),  
  54.                 address  : $("#address").val(),  
  55.                 mobile   : $("#mobile").val()  
  56.         };  
  57.         ajaxDo("/activemq-service/push/client",data);  
  58.     });  
  59.       
  60. function ajaxDo(url,data){  
  61.      $.ajax({  
  62.             url:url ,  
  63.             type: "post",  
  64.             dataType: "json",  
  65.             data: data,  
  66.             success:function(result){  
  67.                if(result.success){  
  68.                    var obj = JSON.stringify(result.data);  
  69.                    alert(obj);  
  70.                }else{  
  71.                    alert(result.msg);  
  72.                }  
  73.             }  
  74.         });  
  75. }     
  76.   
  77. </script>  
  78.   
  79. </body>  
  80. </html>  


現在代碼都已經完成了,那就可以啓動項目了,啓動項目之前首先要啓動activeMQ,然後再啓動activemq-service項目,

打開瀏覽器我們就可以模擬推送內容了:

此時在刷新我們的MQ頁面你就會發現自動創建好了Queue,而且在User那個裏面會有1個消息未被消費掉:


發送端的代碼就這樣已經完成了,明天將會繼續把接收端的代碼寫出來,並且通過websocket推送到前端顯示出來

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章