activeMQ实例在项目中的运用【项目实战系列】

来源:互联网 发布:福山机理书淘宝 编辑:程序博客网 时间:2024/04/28 04:04

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
 在CODE上查看代码片派生到我的代码片
  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
 在CODE上查看代码片派生到我的代码片
  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
 在CODE上查看代码片派生到我的代码片
  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
 在CODE上查看代码片派生到我的代码片
  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
 在CODE上查看代码片派生到我的代码片
  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
 在CODE上查看代码片派生到我的代码片
  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推送到前端显示出来

0 0
原创粉丝点击