Rabbit基于Spring框架实现

来源:互联网 发布:unity3d minecraft 编辑:程序博客网 时间:2024/05/21 11:05

RabbitMq

         消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。其中较为成熟的MQ产品有IBM WEBSPHERE MQ。

RabbitMQ的结构图如下:
RabbitMQ一般的使用场景:
1.作为一种事件绑定监听处理,当client触发了某一个exchange,然后rabbitMq会将取得的数据塞入到queue中。然后由于在配置文件中已经配置好了对于queue的监听接口,当有数据塞入到queue中会触发接口执行程序。
2.一般这种服务也可以作为一种延时处理的操作结合redis,将监听queue的接口绑定到redis中,可以将触发得到的数据保存到redis中然后在通过线程有后台监听数据对象。

Rabbit 数据生产者XML配置文件
[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"  
  4.        xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.        http://www.springframework.org/schema/beans/spring-beans.xsd  
  7.        http://www.springframework.org/schema/rabbit  
  8.        http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">  
  9.   
  10.     <bean id="rabbitUtil" class="com.rabbit.util.RabbitUtil"/>  
  11.     <!-- 这个是一个生产者的信息的配置  -->  
  12.     <!-- 连接服务配置  -->  
  13.     <rabbit:connection-factory id="connectionFactory" addresses="127.0.0.1:5672" publisher-confirms="true"/>  
  14.   
  15.     <!-- spring amqp默认的是jackson 的一个插件,目的将生产者生产的数据转换为json存入消息队列 -->  
  16.     <bean id="jsonMessageConverter"  class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"></bean>  
  17.   
  18.     <!-- spring template声明(作为一个代理-》也就是代理模式中的代理)-->  
  19.     <rabbit:template exchange="my-mq-exchange" id="amqpTemplate"  connection-factory="connectionFactory"  message-converter="jsonMessageConverter"/>  
  20.   
  21.     <!-- 设置rabbit的管理 -->  
  22.     <rabbit:admin connection-factory="connectionFactory"/>  
  23.   
  24.     <!-- queue 队列声明-->  
  25.     <rabbit:queue id="queue_one" durable="true" auto-delete="false" exclusive="false" name="queue_one"/>  
  26.     <rabbit:queue id="queue_tow" durable="true" auto-delete="false" exclusive="false" name="queue_tow"/>  
  27.     <rabbit:queue id="queue_three" durable="true" auto-delete="false" exclusive="false" name="queue_three"/>  
  28.   
  29.   
  30.     <!-- 将队列绑定到交换路由同时与key绑定 -->  
  31.     <rabbit:fanout-exchange name="my-mq-exchange" durable="true" auto-delete="false" id="my-mq-exchange">  
  32.         <rabbit:bindings>  
  33.             <rabbit:binding queue="queue_one"/>  
  34.             <rabbit:binding queue="queue_tow"/>  
  35.         </rabbit:bindings>  
  36.     </rabbit:fanout-exchange>  
  37.   
  38.     <!-- 将与通道绑定的事件与队列绑定 -->  
  39.     <rabbit:fanout-exchange name="mq-exchange2" durable="true" auto-delete="false" id="mq-exchange2">  
  40.         <rabbit:bindings>  
  41.             <rabbit:binding queue="queue_one"/>  
  42.             <rabbit:binding queue="queue_tow"/>  
  43.             <rabbit:binding queue="queue_three"/>  
  44.         </rabbit:bindings>  
  45.     </rabbit:fanout-exchange>  
  46. </beans>  

Rabbit 事件监听XML配置
[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:rabbit="http://www.springframework.org/schema/rabbit"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  5.     http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">  
  6.   
  7.     <!-- 配置spring的队列监听接口(创建监听处理对象) -->  
  8.     <bean id="consumeMessage" class="com.rabbit.test.QueueOneListener" />  
  9.   
  10.     <!-- 连接服务配置  -->  
  11.     <rabbit:connection-factory id="connectionFactory" host="127.0.0.1" port="5672" username="guest" password="guest"/>  
  12.   
  13.     <bean id="jacksonConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"/>  
  14.   
  15.     <!-- 设置rabbit的管理 -->  
  16.     <rabbit:admin connection-factory="connectionFactory"/>  
  17.   
  18.     <!-- 消费者监听队列动态信息 -->  
  19.     <rabbit:listener-container connection-factory="connectionFactory" message-converter="jacksonConverter" acknowledge="none">  
  20.         <rabbit:listener ref="consumeMessage" method="listenOne" queue-names="queue_one" />  
  21.         <rabbit:listener ref="consumeMessage" method="listenTwo" queue-names="queue_tow" />  
  22.         <rabbit:listener ref="consumeMessage" method="listenThree" queue-names="queue_three" />  
  23.         <rabbit:listener ref="consumeMessage" method="listenThree1" queue-names="queue_three" />  
  24.         <rabbit:listener ref="consumeMessage" method="testRedisAnnotation" queue-names="queue_three" />  
  25.     </rabbit:listener-container>  
  26.   
  27. </beans>  
        通过配置rabbit:listener来设置对于某个queue的监听方法的处理设置

封装一个Rabbit实例
[java] view plain copy
  1. package com.rabbit.util;  
  2.   
  3. import org.springframework.amqp.AmqpException;  
  4. import org.springframework.amqp.core.Message;  
  5. import org.springframework.amqp.core.MessageDeliveryMode;  
  6. import org.springframework.amqp.core.MessagePostProcessor;  
  7. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  8. import org.springframework.amqp.rabbit.support.CorrelationData;  
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.stereotype.Component;  
  11.   
  12. /** 
  13.  * 用于提供Rabbit的操作类 
  14.  * Created by Michael Zhao on 14-4-1. 
  15.  */  
  16. @Component  
  17. public class RabbitUtil {  
  18.     private final RabbitTemplate rabbitTemplate;  
  19.   
  20.     @Autowired  
  21.     public RabbitUtil(RabbitTemplate rabbitTemplate){  
  22.         this.rabbitTemplate = rabbitTemplate;  
  23.     }  
  24.   
  25.     public <T> void sendReliable(String exchange, T message) {  
  26.         //实现将message通过json转换&将对象发送  
  27.         //convertAndSend(String exchange, String routingKey, Object message, MessagePostProcessor messagePostProcessor, CorrelationData correlationData)  
  28.         rabbitTemplate.convertAndSend(exchange, "", message, new MessagePostProcessor() {  
  29.             //实现message操作处理实现  
  30.             @Override  
  31.             public Message postProcessMessage(Message message) throws AmqpException {  
  32.                 //设置信息的属性信息&设置发送模式(PERSISTENT:连续的)  
  33.                 message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);  
  34.                 return message;  
  35.             }  
  36.         }, new CorrelationData(String.valueOf(message)));  
  37.     }  
  38. }  

rabbit监听接口层
[java] view plain copy
  1. <span style="font-size:14px;">package com.rabbit.test;  
  2.   
  3. import com.rabbit.ActionInterface.RedisNoResultAction;  
  4. import com.rabbit.annotation.RedisLock;  
  5. import com.rabbit.util.RedisKeys;  
  6. import com.rabbit.util.RedisLockExecute;  
  7. import com.rabbit.util.RedisLockModel;  
  8. import com.rabbit.util.RedisTemplate;  
  9. import org.junit.Before;  
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12. import org.springframework.beans.factory.annotation.Autowired;  
  13. import org.springframework.stereotype.Component;  
  14. import redis.clients.jedis.Jedis;  
  15.   
  16. import java.util.concurrent.TimeUnit;  
  17.   
  18. /** 
  19.  * 用于提供Rabbit监听接口层 
  20.  * Created by Michael Zhao on 14-4-1. 
  21.  */  
  22. @Component  
  23. public class QueueOneListener{  
  24.     @Autowired  
  25.     private RedisTemplate redisTemplate;  
  26.   
  27.     private static final Logger log = LoggerFactory.getLogger(QueueOneListener.class);  
  28.   
  29.     @Before  
  30.     public void setUp(){  
  31.         //销毁所有已经创建的锁  
  32.         RedisLockExecute.destructionLocks(redisTemplate);  
  33.     }  
  34.   
  35.     public void listenOne(Object foo) {  
  36.         System.out.println("listen1");  
  37.         System.out.println(foo);  
  38.     }  
  39.   
  40.     public void listenTwo(Object foo) {  
  41.         System.out.println("listen2");  
  42.         System.out.println(foo);  
  43.     }  
  44.   
  45.     public void listenThree(Object foo) {  
  46.         System.out.println("listen3");  
  47.         System.out.println(foo);  
  48.     }  
  49.   
  50.     public void listenThree1(Object foo){  
  51.         System.out.println("listenThree->"+foo);  
  52.     }  
  53.   
  54.     /** 
  55.      * 实现将信息塞入到redis中 
  56.      * @param foo   对象信息 
  57.      */  
  58.     public void sendRedis(final Object foo){  
  59.         //这个是针对分布式环境下的锁机制  
  60.         RedisLockModel redisLockModel = RedisLockExecute.acquireLock(redisTemplate, RedisKeys.REDIS_TEST, 1000, (int) TimeUnit.SECONDS.toSeconds(10));  
  61.   
  62.         try{  
  63.             if(RedisLockExecute.ACQUIRE_RESULT(redisLockModel)){  
  64.                 redisTemplate.execute(new RedisNoResultAction() {  
  65.                     @Override  
  66.                     public void actionNoResult(Jedis jedis) {  
  67.                         jedis.lpush("sendRedis:" , foo.toString());  
  68.                     }  
  69.                 });  
  70.             }else{  
  71.                 log.debug("acquire lock is failed!");  
  72.             }  
  73.         } catch (Exception e){  
  74.             log.error("send Redis failed , error={}", e);  
  75.         }finally {  
  76.             //释放锁  
  77.             RedisLockExecute.releaseLock(redisTemplate, redisLockModel);  
  78.         }  
  79.     }  
  80.   
  81.     @RedisLock(redisKeys = RedisKeys.REDIS_TEST , maxWait = 10, expiredTime = 1000)  
  82.     public void testRedisAnnotation(final Object foo){  
  83.         try{  
  84.             redisTemplate.execute(new RedisNoResultAction() {  
  85.                 @Override  
  86.                 public void actionNoResult(Jedis jedis) {  
  87.                     jedis.lpush("sendRedis:" , foo.toString());  
  88.                 }  
  89.             });  
  90.         } catch (Exception e){  
  91.             log.error("send Redis failed , error={}", e);  
  92.         }  
  93.     }  
  94. }</span>  

rabbit测试类
[java] view plain copy
  1. package com.rabbit.test;  
  2.   
  3. import com.rabbit.util.RabbitUtil;  
  4. import org.junit.Test;  
  5. import org.junit.runner.RunWith;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.test.context.ContextConfiguration;  
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  9.   
  10. @RunWith(SpringJUnit4ClassRunner.class)  
  11. @ContextConfiguration(locations = {  
  12.         "classpath:/spring/root-context.xml",  
  13.         "classpath:/spring/rabbit-product.xml",  
  14.         "classpath:/spring/rabbit-context.xml",  
  15.         "classpath:/spring/redis-context.xml"  
  16. })  
  17. public class RabbitTest {  
  18.     @Autowired  
  19.     private RabbitUtil rabbitUtil;  
  20.   
  21.     private Integer number = 1;  
  22.   
  23.     @Test  
  24.     public void testRabbit() {  
  25.         while(true){  
  26.             rabbitUtil.sendReliable("my-mq-exchange", number++);  
  27.             rabbitUtil.sendReliable("mq-exchange2", number++);  
  28.   
  29.             try {  
  30.                 Thread.sleep(1000);  
  31.             } catch (InterruptedException e) {  
  32.                 e.printStackTrace();  
  33.             }  
  34.         }  
  35.     }  
  36. }