zoukankan      html  css  js  c++  java
  • spring单元测试下模拟rabbitmq

    gradle添加引用

    compile      'org.springframework.boot:spring-boot-starter-amqp'
    testCompile  'com.github.fridujo:rabbitmq-mock:1.0.10'
    

    添加bean对象

    /**
     * 模拟rabbitmq.
     */
    @ActiveProfiles("test")
    @Component
    public class RabbitMqMock {
      @Bean
      public ConnectionFactory connectionFactory() {
        return new CachingConnectionFactory(MockConnectionFactoryFactory.build());
      }
    }
    

    添加测试的队列

      public static final String LIND_EXCHANGE = "test.basic.exchange";
      public static final String LIND_QUEUE_ROUTEKEY = "test.basic.*";
      public static final String LIND_QUEUE_ROUTEKEY1 = "test.basic.a1";
      public static final String LIND_QUEUE_ROUTEKEY2 = "test.basic.a2";
      
     /**
       * 创建普通交换机.
       */
      @Bean
      public TopicExchange lindExchange() {
        return (TopicExchange) ExchangeBuilder.topicExchange(LIND_EXCHANGE).durable(true)
            .build();
      }
    
     @Bean
      public Queue key1() {
        return new Queue(LIND_QUEUE_ROUTEKEY1);
      }
    
      @Bean
      public Queue key2() {
        return new Queue(LIND_QUEUE_ROUTEKEY2);
      }
    
      /**
       * 绑定了routekey,一个routekey可以被多个队列绑定,类似于广播.
       *
       * @return
       */
      @Bean
      public Binding bindBuildersRouteKey1() {
        return BindingBuilder.bind(key1())
            .to(lindExchange())
            .with(LIND_QUEUE_ROUTEKEY);
      }
    
      /**
       * bind.
       *
       * @return
       */
      @Bean
      public Binding bindBuildersRouteKey2() {
        return BindingBuilder.bind(key2())
            .to(lindExchange())
            .with(LIND_QUEUE_ROUTEKEY);
      }
      @Autowired
      private RabbitTemplate rabbitTemplate;
    
      /**
       * 发送拨打电话消息.
       */
      public void publish(String message) {
        try {
          rabbitTemplate
              .convertAndSend(MqConfig.LIND_EXCHANGE, MqConfig.LIND_QUEUE_ROUTEKEY,
                  message);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      
        /**
       * subscriber.
       *
       * @param data .
       */
      @RabbitListener(queues = MqConfig.LIND_DEAD_QUEUE)
      public void customerSign(String data) {
        try {
    
          logger.info("从队列拿到数据 :{}", data);
    
        } catch (Exception ex) {
          logger.error("签约同步异常", ex);
        }
      }
    

    总结:通过上面的几行代码,我们可以对rabbitmq队列在测试环境中去模拟,方便了我们的测试,而这种方法比org.apache.qpid:qpid-broker:6.1.2这个包要方便的多,当然这个包也支持其它的qpid协议的队列。

  • 相关阅读:
    跟小静学CLR via C#(12)委托Delegate
    跟小静读CLR via C#(02)基元类型、引用类型、值类型
    跟小静读CLR via C#(07)静态类,分部类
    jQuery折叠菜单
    ajax调用后台Datatable
    跟小静读CLR via C#(11)无参属性、索引器
    跟小静读CLR via C#(08)操作符
    跟小静读CLR via C#(05) 访问限定、数据成员
    AjaxPro排错指南
    跟小静读CLR via C#(14)可空值类型,关于?和??的故事
  • 原文地址:https://www.cnblogs.com/lori/p/10937351.html
Copyright © 2011-2022 走看看