@Test
 public void testConnectionFactoryBackOff() {
   load(TestConfiguration2.class);
   RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class);
   CachingConnectionFactory connectionFactory =
       this.context.getBean(CachingConnectionFactory.class);
   assertThat(connectionFactory).isEqualTo(rabbitTemplate.getConnectionFactory());
   assertThat(connectionFactory.getHost()).isEqualTo("otherserver");
   assertThat(connectionFactory.getPort()).isEqualTo(8001);
 }
  @After
  public void clear() throws Exception {
    // Wait for broker communication to finish before trying to stop container
    Thread.sleep(300L);
    logger.debug("Shutting down at end of test");
    if (container != null) {
      container.shutdown();
    }

    ((DisposableBean) template.getConnectionFactory()).destroy();
  }
 private SimpleMessageListenerContainer createContainer(Object listener) {
   SimpleMessageListenerContainer container =
       new SimpleMessageListenerContainer(template.getConnectionFactory());
   container.setMessageListener(new MessageListenerAdapter(listener));
   container.setQueueNames(queue.getName());
   container.setTxSize(txSize);
   container.setPrefetchCount(txSize);
   container.setConcurrentConsumers(concurrentConsumers);
   container.setChannelTransacted(transactional);
   container.setAcknowledgeMode(AcknowledgeMode.AUTO);
   container.afterPropertiesSet();
   container.start();
   return container;
 }
  @RequestMapping("/haveRabbitConnection")
  public @ResponseBody String haveRabbitMqConnection() {
    Boolean haveRabbit = false;
    if (rabbitTemplate != null) {

      try {
        ConnectionFactory connectionFactory = rabbitTemplate.getConnectionFactory();
        connectionFactory.createConnection();
        haveRabbit = true;
      } catch (AmqpException ae) {
        haveRabbit = false;
      }
    }
    return "{ \"haveRabbitMqConnection\" : \"" + haveRabbit + "\"}";
  }
Exemplo n.º 5
0
  /**
   * 生成消息
   *
   * @param content 消息内容
   * @param queueName 队列名称
   * @return
   * @author Ethan
   * @create-time 2015年5月6日 下午4:20:50
   */
  private Message generateMessage(String content, String queueName) {

    String appId =
        rabbitTemplate.getConnectionFactory().getVirtualHost()
            + "/"
            + queueName; // 将虚拟主机和队列名称设置为appId

    // 发送消息
    MessageProperties props =
        MessagePropertiesBuilder.newInstance()
            .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
            .setContentEncoding("UTF-8")
            .setTimestamp(new Date())
            .setHeader("", "")
            .setAppId(appId) // 设置发送中心系统识别
            .build();
    Message message = MessageBuilder.withBody(content.getBytes()).andProperties(props).build();
    return message;
  }
  @Test
  public void testArgumentsQueue() throws Exception {

    Queue queue = beanFactory.getBean("arguments", Queue.class);
    assertNotNull(queue);

    RabbitTemplate template =
        new RabbitTemplate(new CachingConnectionFactory(BrokerTestUtils.getPort()));
    RabbitAdmin rabbitAdmin = new RabbitAdmin(template.getConnectionFactory());
    rabbitAdmin.deleteQueue(queue.getName());
    rabbitAdmin.declareQueue(queue);

    assertEquals(100L, queue.getArguments().get("x-message-ttl"));
    template.convertAndSend(queue.getName(), "message");

    Thread.sleep(200);
    String result = (String) template.receiveAndConvert(queue.getName());
    assertEquals(null, result);
  }
 @Test
 public void testDefaultRabbitConfiguration() {
   load(TestConfiguration.class);
   RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class);
   RabbitMessagingTemplate messagingTemplate = this.context.getBean(RabbitMessagingTemplate.class);
   CachingConnectionFactory connectionFactory =
       this.context.getBean(CachingConnectionFactory.class);
   DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory);
   RabbitAdmin amqpAdmin = this.context.getBean(RabbitAdmin.class);
   assertThat(rabbitTemplate.getConnectionFactory()).isEqualTo(connectionFactory);
   assertThat(getMandatory(rabbitTemplate)).isFalse();
   assertThat(messagingTemplate.getRabbitTemplate()).isEqualTo(rabbitTemplate);
   assertThat(amqpAdmin).isNotNull();
   assertThat(connectionFactory.getHost()).isEqualTo("localhost");
   assertThat(dfa.getPropertyValue("publisherConfirms")).isEqualTo(false);
   assertThat(dfa.getPropertyValue("publisherReturns")).isEqualTo(false);
   assertThat(this.context.containsBean("rabbitListenerContainerFactory"))
       .as("Listener container factory should be created by default")
       .isTrue();
 }
 private SimpleMessageListenerContainer createContainer(Object listener) {
   SimpleMessageListenerContainer container =
       new SimpleMessageListenerContainer(template.getConnectionFactory());
   container.setMessageListener(listener);
   container.setQueueNames(queue.getName());
   container.setTxSize(txSize);
   container.setPrefetchCount(txSize);
   container.setConcurrentConsumers(concurrentConsumers);
   container.setChannelTransacted(transactional);
   container.setAcknowledgeMode(acknowledgeMode);
   // requires RabbitMQ 3.2.x
   //		container.setConsumerArguments(Collections. <String, Object> singletonMap("x-priority",
   // Integer.valueOf(10)));
   if (externalTransaction) {
     container.setTransactionManager(new TestTransactionManager());
   }
   container.afterPropertiesSet();
   container.start();
   return container;
 }
 @Test
 public void testListenerSunnyDay() throws Exception {
   CountDownLatch latch = new CountDownLatch(messageCount);
   for (int i = 0; i < messageCount; i++) {
     template.convertAndSend(queue.getName(), i + "foo");
   }
   SimpleMessageListenerContainer container =
       new SimpleMessageListenerContainer(template.getConnectionFactory());
   container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch)));
   container.setChannelTransacted(transactional);
   container.setConcurrentConsumers(concurrentConsumers);
   container.setQueueName(queue.getName());
   container.afterPropertiesSet();
   container.start();
   try {
     boolean waited = latch.await(50, TimeUnit.MILLISECONDS);
     assertFalse("Expected time out waiting for message", waited);
     container.stop();
     Thread.sleep(500L);
     container.start();
     if (transactional) {
       waited = latch.await(5, TimeUnit.SECONDS);
       assertTrue("Timed out waiting for message", waited);
     } else {
       waited = latch.await(500, TimeUnit.MILLISECONDS);
       // If non-transactional we half expect to lose messages
       assertFalse("Expected time out waiting for message", waited);
     }
   } finally {
     // Wait for broker communication to finish before trying to stop
     // container
     Thread.sleep(300L);
     container.shutdown();
   }
   assertNull(template.receiveAndConvert(queue.getName()));
 }
  private void doTestRetry(
      int messageCount, int txSize, int failFrequency, int concurrentConsumers, boolean stateful)
      throws Exception {

    int failedMessageCount =
        messageCount / failFrequency + (messageCount % failFrequency == 0 ? 0 : 1);

    RabbitTemplate template = createTemplate(concurrentConsumers);
    for (int i = 0; i < messageCount; i++) {
      template.convertAndSend(queue.getName(), i);
    }

    final SimpleMessageListenerContainer container =
        new SimpleMessageListenerContainer(template.getConnectionFactory());
    PojoListener listener = new PojoListener(failFrequency);
    container.setMessageListener(new MessageListenerAdapter(listener));
    container.setAcknowledgeMode(AcknowledgeMode.AUTO);
    container.setChannelTransacted(true);
    container.setTxSize(txSize);
    container.setConcurrentConsumers(concurrentConsumers);

    final CountDownLatch latch = new CountDownLatch(failedMessageCount);
    container.setAdviceChain(new Advice[] {createRetryInterceptor(latch, stateful)});

    container.setQueueNames(queue.getName());
    container.afterPropertiesSet();
    container.start();

    try {

      int timeout = Math.min(1 + 2 * messageCount / concurrentConsumers, 30);

      final int count = messageCount;
      logger.debug("Waiting for messages with timeout = " + timeout + " (s)");
      Executors.newSingleThreadExecutor()
          .execute(
              () -> {
                while (container.getActiveConsumerCount() > 0) {
                  try {
                    Thread.sleep(100L);
                  } catch (InterruptedException e) {
                    latch.countDown();
                    Thread.currentThread().interrupt();
                    return;
                  }
                }
                for (int i = 0; i < count; i++) {
                  latch.countDown();
                }
              });
      boolean waited = latch.await(timeout, TimeUnit.SECONDS);
      logger.info("All messages recovered: " + waited);
      assertEquals(concurrentConsumers, container.getActiveConsumerCount());
      assertTrue("Timed out waiting for messages", waited);

      // Retried each failure 3 times (default retry policy)...
      assertEquals(3 * failedMessageCount, listener.getCount());

      // All failed messages recovered
      assertEquals(null, template.receiveAndConvert(queue.getName()));

    } finally {
      container.shutdown();
      ((DisposableBean) template.getConnectionFactory()).destroy();

      assertEquals(0, container.getActiveConsumerCount());
    }
  }