// Even though Spring boot defines this we end up with a circular dependency in Heroku so we need
 // to define it here again for some reason.
 @Bean
 public RabbitTemplate rabbitTemplate(
     CachingConnectionFactory connectionFactory, MessageConverter messageConverter) {
   RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
   rabbitTemplate.setMessageConverter(messageConverter);
   return rabbitTemplate;
 }
  /** - */
  @Test
  public void test() throws Exception {

    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    when(mockChannel.isOpen()).thenReturn(true);

    Message msg =
        this.messageConverter.toMessage(
            createFieldChangedEvent(
                "/asset/assetMeter/crank-frame-dischargepressure", //$NON-NLS-1$
                "/asset/assetMeter/crank-frame-dischargepressure", //$NON-NLS-1$
                "/asset/compressor-2015", //$NON-NLS-1$
                StringUtil.parseDate("2012-09-11T07:16:13"), // $NON-NLS-1$
                null,
                null),
            null);

    final RabbitTemplate fieldChangedEventTemplate =
        new RabbitTemplate(new CachingConnectionFactory(mockConnectionFactory));
    fieldChangedEventTemplate.convertAndSend("fieldchangedeventMainQ", msg); // $NON-NLS-1$
  }
 @Test
 public void testRabbitTemplateBackOff() {
   load(TestConfiguration3.class);
   RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class);
   assertThat(rabbitTemplate.getMessageConverter())
       .isEqualTo(this.context.getBean("testMessageConverter"));
 }
 private RabbitTemplate determineRabbitTemplate(RabbitPropertiesAccessor properties) {
   RabbitTemplate rabbitTemplate = null;
   if (properties.isBatchingEnabled(this.defaultBatchingEnabled)) {
     BatchingStrategy batchingStrategy =
         new SimpleBatchingStrategy(
             properties.getBatchSize(this.defaultBatchSize),
             properties.geteBatchBufferLimit(this.defaultBatchBufferLimit),
             properties.getBatchTimeout(this.defaultBatchTimeout));
     rabbitTemplate =
         new BatchingRabbitTemplate(
             batchingStrategy,
             getApplicationContext()
                 .getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class));
     rabbitTemplate.setConnectionFactory(this.connectionFactory);
   }
   if (properties.isCompress(this.defaultCompress)) {
     if (rabbitTemplate == null) {
       rabbitTemplate = new RabbitTemplate(this.connectionFactory);
     }
     rabbitTemplate.setBeforePublishPostProcessors(this.compressingPostProcessor);
     rabbitTemplate.afterPropertiesSet();
   }
   if (rabbitTemplate == null) {
     rabbitTemplate = this.rabbitTemplate;
   }
   return rabbitTemplate;
 }
 private void doListenerWithExceptionTest(CountDownLatch latch, Object listener) throws Exception {
   container = createContainer(listener);
   if (acknowledgeMode.isTransactionAllowed()) {
     // Should only need one message if it is going to fail
     for (int i = 0; i < concurrentConsumers; i++) {
       template.convertAndSend(queue.getName(), i + "foo");
     }
   } else {
     for (int i = 0; i < messageCount; i++) {
       template.convertAndSend(queue.getName(), i + "foo");
     }
   }
   try {
     boolean waited = latch.await(10 + Math.max(1, messageCount / 10), TimeUnit.SECONDS);
     assertTrue("Timed out waiting for message", waited);
   } finally {
     // Wait for broker communication to finish before trying to stop
     // container
     Thread.sleep(300L);
     container.shutdown();
     Thread.sleep(300L);
   }
   if (acknowledgeMode.isTransactionAllowed()) {
     assertNotNull(template.receiveAndConvert(queue.getName()));
   } else {
     assertNull(template.receiveAndConvert(queue.getName()));
   }
 }
 @Bean
 public RabbitTemplate rabbitTemplate() throws Throwable {
   RabbitTemplate rabbitTemplate =
       new RabbitTemplate(rabbitConnectionFactoryConfiguration.connectionFactory());
   rabbitTemplate.setMessageConverter(mc());
   return rabbitTemplate;
 }
 @Test
 public void testRabbitTemplateMessageConverters() {
   load(MessageConvertersConfiguration.class);
   RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class);
   assertThat(rabbitTemplate.getMessageConverter())
       .isSameAs(this.context.getBean("myMessageConverter"));
   DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate);
   assertThat(dfa.getPropertyValue("retryTemplate")).isNull();
 }
 private void doSunnyDayTest(CountDownLatch latch, Object listener) throws Exception {
   container = createContainer(listener);
   for (int i = 0; i < messageCount; i++) {
     template.convertAndSend(queue.getName(), i + "foo");
   }
   boolean waited = latch.await(Math.max(10, messageCount / 20), TimeUnit.SECONDS);
   assertTrue("Timed out waiting for message", waited);
   assertNull(template.receiveAndConvert(queue.getName()));
 }
 @Override
 protected void verifyOnDemandQueues(MessageChannel y3, MessageChannel z3) {
   RabbitTemplate template = new RabbitTemplate(rabbitAvailableRule.getResource());
   Object y = template.receiveAndConvert("xdbus.queue:y");
   assertNotNull(y);
   assertEquals("y", y);
   Object z = template.receiveAndConvert("xdbus.queue:z");
   assertNotNull(z);
   assertEquals("z", z);
 }
 @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);
 }
Esempio n. 11
0
 /**
  * 发送消息
  *
  * @param queue
  * @param content
  * @author Ethan
  * @datetime 2015年11月9日 下午8:24:00
  */
 public void sendMessage(String queue, String content) {
   try {
     String routingKey = queue;
     // 发送消息
     rabbitTemplate.setQueue(queue);
     rabbitTemplate.setRoutingKey(routingKey);
     rabbitTemplate.send(this.generateMessage(content, queue));
   } catch (AmqpException e) {
     e.printStackTrace();
   }
 }
Esempio n. 12
0
  @Override
  public void sendCommand(final NFVMessage nfvMessage, String tempDestination) {
    log.trace(
        "Sending NFVMessage with action: "
            + nfvMessage.getAction()
            + " to tempQueue: "
            + tempDestination);

    rabbitTemplate.setReplyQueue(new Queue(tempDestination));
    rabbitTemplate.convertAndSend(tempDestination, gson.toJson(nfvMessage));
  }
 @Test
 public void testListenerTransactionalSunnyDay() throws Exception {
   transactional = true;
   CountDownLatch latch = new CountDownLatch(messageCount);
   container = createContainer(new TestListener(latch, false));
   for (int i = 0; i < messageCount; i++) {
     template.convertAndSend(queue.getName(), i + "foo");
   }
   int timeout = Math.min(1 + messageCount / (4 * concurrentConsumers), 30);
   logger.debug("Waiting for messages with timeout = " + timeout + " (s)");
   boolean waited = latch.await(timeout, TimeUnit.SECONDS);
   assertTrue("Timed out waiting for message", waited);
   assertNull(template.receiveAndConvert(queue.getName()));
 }
  @Test
  public void testAutoBindDLQwithRepublish() throws Exception {
    // pre-declare the queue with dead-lettering, users can also use a policy
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());
    Map<String, Object> args = new HashMap<String, Object>();
    args.put("x-dead-letter-exchange", "xdbustest.DLX");
    Queue queue = new Queue("xdbustest.dlqpubtest", true, false, false, args);
    admin.declareQueue(queue);

    MessageBus bus = getMessageBus();
    Properties properties = new Properties();
    properties.put("prefix", "xdbustest.");
    properties.put("autoBindDLQ", "true");
    properties.put("republishToDLQ", "true");
    properties.put("maxAttempts", "1"); // disable retry
    properties.put("requeue", "false");
    DirectChannel moduleInputChannel = new DirectChannel();
    moduleInputChannel.setBeanName("dlqPubTest");
    moduleInputChannel.subscribe(
        new MessageHandler() {

          @Override
          public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
          }
        });
    bus.bindConsumer("dlqpubtest", moduleInputChannel, properties);

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.convertAndSend("", "xdbustest.dlqpubtest", "foo");

    int n = 0;
    while (n++ < 100) {
      org.springframework.amqp.core.Message deadLetter =
          template.receive("xdbustest.dlqpubtest.dlq");
      if (deadLetter != null) {
        assertEquals("foo", new String(deadLetter.getBody()));
        assertNotNull(deadLetter.getMessageProperties().getHeaders().get("x-exception-stacktrace"));
        break;
      }
      Thread.sleep(100);
    }
    assertTrue(n < 100);

    bus.unbindConsumer("dlqpubtest", moduleInputChannel);
    admin.deleteQueue("xdbustest.dlqpubtest.dlq");
    admin.deleteQueue("xdbustest.dlqpubtest");
    admin.deleteExchange("xdbustest.DLX");
  }
 private RabbitTemplate createTemplate(int concurrentConsumers) {
   RabbitTemplate template = new RabbitTemplate();
   CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
   connectionFactory.setHost("localhost");
   connectionFactory.setChannelCacheSize(concurrentConsumers);
   connectionFactory.setPort(BrokerTestUtils.getPort());
   template.setConnectionFactory(connectionFactory);
   if (messageConverter == null) {
     SimpleMessageConverter messageConverter = new SimpleMessageConverter();
     messageConverter.setCreateMessageIds(true);
     this.messageConverter = messageConverter;
   }
   template.setMessageConverter(messageConverter);
   return template;
 }
 @Before
 public void declareQueue() {
   CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
   connectionFactory.setChannelCacheSize(concurrentConsumers);
   // connectionFactory.setPort(5673);
   template.setConnectionFactory(connectionFactory);
 }
 @Before
 public void createConnectionFactory() {
   CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
   connectionFactory.setChannelCacheSize(concurrentConsumers);
   connectionFactory.setPort(BrokerTestUtils.getPort());
   template.setConnectionFactory(connectionFactory);
 }
Esempio n. 18
0
 /**
  * Method to set the Jackson2JsonMessageConverter.
  *
  * @return the Jackson2JsonMessageConverter
  */
 @Bean
 public MessageConverter jsonMessageConverter() {
   final Jackson2JsonMessageConverter jackson2JsonMessageConverter =
       new Jackson2JsonMessageConverter();
   rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter);
   return jackson2JsonMessageConverter;
 }
 @Before
 public void declareQueue() {
   CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
   connectionFactory.setHost("localhost");
   connectionFactory.setChannelCacheSize(concurrentConsumers);
   connectionFactory.setPort(BrokerTestUtils.getPort());
   template.setConnectionFactory(connectionFactory);
 }
  /**
   * Sends message to RabbitMQ and waits for response
   *
   * @param payload The message
   * @return response from RabbitMQ
   */
  public Object sendAndReceive(Object payload) {

    String routingKey = payload.getClass().getCanonicalName();

    log.debug("Sending message - routingKey: {}, payload: {}", routingKey, payload);

    return rabbitTemplate.convertSendAndReceive(routingKey, payload, messagePostProcessor);
  }
  @Test
  public void testDurablePubSubWithAutoBindDLQ() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());

    MessageBus bus = getMessageBus();
    Properties properties = new Properties();
    properties.put("prefix", "xdbustest.");
    properties.put("autoBindDLQ", "true");
    properties.put("durableSubscription", "true");
    properties.put("maxAttempts", "1"); // disable retry
    properties.put("requeue", "false");
    DirectChannel moduleInputChannel = new DirectChannel();
    moduleInputChannel.setBeanName("durableTest");
    moduleInputChannel.subscribe(
        new MessageHandler() {

          @Override
          public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
          }
        });
    bus.bindPubSubConsumer("teststream.tap:stream:durabletest.0", moduleInputChannel, properties);

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.convertAndSend("xdbustest.topic.tap:stream:durabletest.0", "", "foo");

    int n = 0;
    while (n++ < 100) {
      Object deadLetter =
          template.receiveAndConvert("xdbustest.teststream.tap:stream:durabletest.0.dlq");
      if (deadLetter != null) {
        assertEquals("foo", deadLetter);
        break;
      }
      Thread.sleep(100);
    }
    assertTrue(n < 100);

    bus.unbindConsumer("teststream.tap:stream:durabletest.0", moduleInputChannel);
    assertNotNull(admin.getQueueProperties("xdbustest.teststream.tap:stream:durabletest.0.dlq"));
    admin.deleteQueue("xdbustest.teststream.tap:stream:durabletest.0.dlq");
    admin.deleteQueue("xdbustest.teststream.tap:stream:durabletest.0");
    admin.deleteExchange("xdbustest.topic.tap:stream:durabletest.0");
    admin.deleteExchange("xdbustest.DLX");
  }
Esempio n. 22
0
  public void incPostHits(Long postId) {
    incPageViews("/posts/" + postId);
    changeList.add(CACHE_CHANGE_LIST, postId);

    if (getPostHits(postId) % 100 == 0) {
      rabbitTemplate.convertAndSend(
          RabbitmqConfiguration.QUEUE_UPDATE_POST_SCORE, postService.getPost(postId));
    }
  }
  private void doTest(int concurrentConsumers, ContainerConfigurer configurer) {
    int messageCount = 10;
    RabbitTemplate template = new RabbitTemplate();
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setHost("localhost");
    connectionFactory.setChannelCacheSize(concurrentConsumers);
    connectionFactory.setPort(BrokerTestUtils.getPort());
    template.setConnectionFactory(connectionFactory);
    SimpleMessageConverter messageConverter = new SimpleMessageConverter();
    messageConverter.setCreateMessageIds(true);
    template.setMessageConverter(messageConverter);
    for (int i = 0; i < messageCount; i++) {
      template.convertAndSend(queue1.getName(), new Integer(i));
      template.convertAndSend(queue2.getName(), new Integer(i));
    }
    final SimpleMessageListenerContainer container =
        new SimpleMessageListenerContainer(connectionFactory);
    final CountDownLatch latch = new CountDownLatch(messageCount * 2);
    PojoListener listener = new PojoListener(latch);
    container.setMessageListener(new MessageListenerAdapter(listener));
    container.setAcknowledgeMode(AcknowledgeMode.AUTO);
    container.setChannelTransacted(true);
    container.setConcurrentConsumers(concurrentConsumers);
    configurer.configure(container);
    container.afterPropertiesSet();
    container.start();
    try {
      int timeout = Math.min(1 + messageCount / concurrentConsumers, 30);
      boolean waited = latch.await(timeout, TimeUnit.SECONDS);
      logger.info("All messages recovered: " + waited);
      assertEquals(concurrentConsumers, container.getActiveConsumerCount());
      assertTrue("Timed out waiting for messages", waited);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new IllegalStateException("unexpected interruption");
    } finally {
      container.shutdown();
      assertEquals(0, container.getActiveConsumerCount());
    }
    assertNull(template.receiveAndConvert(queue1.getName()));
    assertNull(template.receiveAndConvert(queue2.getName()));

    connectionFactory.destroy();
  }
  /**
   * Sends message to RabbitMQ
   *
   * @param payload The message
   * @param identifier The message's identifier
   */
  public void send(Object payload, String identifier) {

    String routingKey = payload.getClass().getCanonicalName();

    log.debug(
        "Sending message - routingKey: {}, id: {}, payload: {}", routingKey, identifier, payload);

    rabbitTemplate.convertAndSend(
        routingKey, payload, messagePostProcessor, new CorrelationData(identifier));
  }
  @RequestMapping("/vehicleInfo")
  public @ResponseBody VehicleInfo vehicleInfo() throws Exception {

    String json = new String((byte[]) rabbitTemplate.receiveAndConvert(queueName));

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    return mapper.readValue(json, VehicleInfo.class);
  }
  @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);
  }
  @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();
  }
 @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();
 }
  /**
   * Constructor
   *
   * @param host Host name
   * @param port Host connection port
   * @param username Connection user name
   * @param password Connection password
   * @param virtualHost RabbitMQ virtual host
   * @param exchangeName RabbitMQ exchange name
   * @param queueName Queue name
   */
  public RabbitMQTopicQueueProducer(
      String host,
      int port,
      String username,
      String password,
      String virtualHost,
      String exchangeName,
      String queueName) {
    super();

    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setVirtualHost(virtualHost);
    RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
    rabbitTemplate.setExchange(exchangeName);
    rabbitTemplate.setQueue(queueName);

    this.setConnectionFactory(connectionFactory);
    this.setRabbitTemplate(rabbitTemplate);
  }
  @Override
  public Spy spyOn(final String queue) {
    final RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.setAfterReceivePostProcessors(new DelegatingDecompressingPostProcessor());
    return new Spy() {

      @Override
      public Object receive(boolean expectNull) throws Exception {
        if (expectNull) {
          Thread.sleep(50);
          return template.receiveAndConvert("xdbus." + queue);
        }
        Object bar = null;
        int n = 0;
        while (n++ < 100 && bar == null) {
          bar = template.receiveAndConvert("xdbus." + queue);
          Thread.sleep(100);
        }
        assertTrue("Message did not arrive in RabbitMQ", n < 100);
        return bar;
      }
    };
  }