rabbitmq与springmvc结合

转载自:https://blog.csdn.net/michaelzhaozero/article/details/23741511

RabbitMq

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

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

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

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

封装一个Rabbit实例

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

rabbit监听接口层

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

rabbit测试类

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

提示:如果想要运行着一些代码,请设置对应的Spring环境。对于redis的配置这边可以不设置直接去除。redis的介绍将在下一遍中涉及。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值