Example usage for org.springframework.amqp.rabbit.core RabbitTemplate convertAndSend

List of usage examples for org.springframework.amqp.rabbit.core RabbitTemplate convertAndSend

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.core RabbitTemplate convertAndSend.

Prototype

@Override
    public void convertAndSend(Object message, MessagePostProcessor messagePostProcessor,
            CorrelationData correlationData) throws AmqpException 

Source Link

Usage

From source file:org.springframework.amqp.rabbit.core.RabbitTemplatePublisherCallbacksIntegrationTests.java

private void testPublisherConfirmCloseConcurrency(final int closeAfter) throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel1 = mock(Channel.class);
    final AtomicLong seq1 = new AtomicLong();
    doAnswer(invocation -> seq1.incrementAndGet()).when(mockChannel1).getNextPublishSeqNo();

    Channel mockChannel2 = mock(Channel.class);
    when(mockChannel2.isOpen()).thenReturn(true);
    final AtomicLong seq2 = new AtomicLong();
    doAnswer(invocation -> seq2.incrementAndGet()).when(mockChannel2).getNextPublishSeqNo();

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel1, mockChannel2);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setPublisherConfirms(true);/*from  w  w  w .  jav  a2 s. c o  m*/
    final RabbitTemplate template = new RabbitTemplate(ccf);

    final CountDownLatch confirmed = new CountDownLatch(1);
    template.setConfirmCallback((correlationData, ack, cause) -> confirmed.countDown());
    ExecutorService exec = Executors.newSingleThreadExecutor();
    final AtomicInteger sent = new AtomicInteger();
    doAnswer(invocation -> sent.incrementAndGet() < closeAfter).when(mockChannel1).isOpen();
    final CountDownLatch sentAll = new CountDownLatch(1);
    exec.execute(() -> {
        for (int i = 0; i < 1000; i++) {
            try {
                template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc"));
            } catch (AmqpException e) {
            }
        }
        sentAll.countDown();
    });
    assertTrue(sentAll.await(10, TimeUnit.SECONDS));
    assertTrue(confirmed.await(10, TimeUnit.SECONDS));
}

From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java

@SuppressWarnings("rawtypes")
@Test//w ww .ja v a2  s  .  c  o m
public void testWithNoId() throws Exception {
    // 2 messages; each retried once by missing id interceptor
    this.latch = new CountDownLatch(4);
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml",
            this.getClass());
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setStatefulRetryFatalWithNullMessageId(false);
    container.setMessageListener(new MessageListenerAdapter(new POJO()));
    container.setQueueNames("retry.test.queue");

    StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean();

    // use an external template so we can share his cache
    RetryTemplate retryTemplate = new RetryTemplate();
    RetryContextCache cache = spy(new MapRetryContextCache());
    retryTemplate.setRetryContextCache(cache);
    fb.setRetryOperations(retryTemplate);

    Advice retryInterceptor = fb.getObject();
    container.setAdviceChain(retryInterceptor);
    container.start();

    template.convertAndSend("retry.test.exchange", "retry.test.binding", "Hello, world!");
    template.convertAndSend("retry.test.exchange", "retry.test.binding", "Hello, world!");
    try {
        assertTrue(latch.await(30, TimeUnit.SECONDS));
        Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map");
        int n = 0;
        while (n++ < 100 && map.size() != 0) {
            Thread.sleep(100);
        }
        verify(cache, never()).put(any(), any(RetryContext.class));
        verify(cache, never()).remove(any());
        assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size());
    } finally {
        container.stop();
        ctx.close();
    }
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testDurablePubSubWithAutoBindDLQ() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());

    RabbitTestBinder binder = getBinder();

    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.getExtension().setDurableSubscription(true);
    consumerProperties.setMaxAttempts(1); // disable retry
    DirectChannel moduleInputChannel = createBindableChannel("input",
            createConsumerBindingProperties(consumerProperties));
    moduleInputChannel.setBeanName("durableTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override/*www . j a va 2  s  . c o m*/
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("durabletest.0", "tgroup", moduleInputChannel,
            consumerProperties);

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.convertAndSend(TEST_PREFIX + "durabletest.0", "", "foo");

    int n = 0;
    while (n++ < 100) {
        Object deadLetter = template.receiveAndConvert(TEST_PREFIX + "durabletest.0.tgroup.dlq");
        if (deadLetter != null) {
            assertThat(deadLetter).isEqualTo("foo");
            break;
        }
        Thread.sleep(100);
    }
    assertThat(n).isLessThan(100);

    consumerBinding.unbind();
    assertThat(admin.getQueueProperties(TEST_PREFIX + "durabletest.0.tgroup.dlq")).isNotNull();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testAutoBindDLQ() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.setMaxAttempts(1); // disable retry
    consumerProperties.getExtension().setDurableSubscription(true);
    BindingProperties bindingProperties = createConsumerBindingProperties(consumerProperties);
    DirectChannel moduleInputChannel = createBindableChannel("input", bindingProperties);
    moduleInputChannel.setBeanName("dlqTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override//from w  ww  .  ja v  a 2  s  .c  o  m
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("dlqtest", "default", moduleInputChannel,
            consumerProperties);

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.convertAndSend("", TEST_PREFIX + "dlqtest.default", "foo");

    int n = 0;
    while (n++ < 100) {
        Object deadLetter = template.receiveAndConvert(TEST_PREFIX + "dlqtest.default.dlq");
        if (deadLetter != null) {
            assertThat(deadLetter).isEqualTo("foo");
            break;
        }
        Thread.sleep(100);
    }
    assertThat(n).isLessThan(100);

    consumerBinding.unbind();

    ApplicationContext context = TestUtils.getPropertyValue(binder,
            "binder.provisioningProvider.autoDeclareContext", ApplicationContext.class);
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.binding")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq.binding")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq")).isFalse();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@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", TEST_PREFIX + "DLX");
    args.put("x-dead-letter-routing-key", TEST_PREFIX + "dlqpubtest.default");
    Queue queue = new Queue(TEST_PREFIX + "dlqpubtest.default", true, false, false, args);
    admin.declareQueue(queue);//ww w .  ja  v  a  2  s  .  co m

    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.getExtension().setRepublishToDlq(true);
    consumerProperties.setMaxAttempts(1); // disable retry
    consumerProperties.getExtension().setDurableSubscription(true);
    DirectChannel moduleInputChannel = createBindableChannel("input",
            createConsumerBindingProperties(consumerProperties));
    moduleInputChannel.setBeanName("dlqPubTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo.dlqpubtest", "foo", moduleInputChannel,
            consumerProperties);

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

    int n = 0;
    while (n++ < 100) {
        org.springframework.amqp.core.Message deadLetter = template
                .receive(TEST_PREFIX + "foo.dlqpubtest.foo.dlq");
        if (deadLetter != null) {
            assertThat(new String(deadLetter.getBody())).isEqualTo("foo");
            assertThat(deadLetter.getMessageProperties().getHeaders()).containsKey(("x-exception-stacktrace"));
            break;
        }
        Thread.sleep(100);
    }
    assertThat(n).isLessThan(100);

    consumerBinding.unbind();
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java

@Test
public void testDurablePubSubWithAutoBindDLQ() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());

    MessageBus bus = getMessageBus();/*from w w w. j  av a2  s.  c o m*/
    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");
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java

@Test
public void testAutoBindDLQ() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());

    MessageBus bus = getMessageBus();/*from   ww w  .  ja v  a2 s .  com*/
    Properties properties = new Properties();
    properties.put("prefix", "xdbustest.");
    properties.put("autoBindDLQ", "true");
    properties.put("maxAttempts", "1"); // disable retry
    properties.put("requeue", "false");
    DirectChannel moduleInputChannel = new DirectChannel();
    moduleInputChannel.setBeanName("dlqTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    bus.bindConsumer("dlqtest", moduleInputChannel, properties);

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

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

    bus.unbindConsumer("dlqtest", moduleInputChannel);
    admin.deleteQueue("xdbustest.dlqtest.dlq");
    admin.deleteQueue("xdbustest.dlqtest");
    admin.deleteExchange("xdbustest.DLX");
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java

@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);/*  ww  w .j a v a2s  .c  o m*/

    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");
}

From source file:org.springframework.xd.dirt.integration.rabbit.RabbitMessageBusTests.java

@Test
public void testAutoBindDLQ() 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.dlqtest", true, false, false, args);
    admin.declareQueue(queue);// www.ja  va  2s. c  o m

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

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    bus.bindConsumer("dlqtest", moduleInputChannel, properties);

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

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

    bus.unbindConsumer("dlqtest", moduleInputChannel);
    admin.deleteQueue("xdbustest.dlqtest.dlq");
    admin.deleteQueue("xdbustest.dlqtest");
    admin.deleteExchange("xdbustest.DLX");
}