Example usage for org.springframework.integration.channel DirectChannel subscribe

List of usage examples for org.springframework.integration.channel DirectChannel subscribe

Introduction

In this page you can find the example usage for org.springframework.integration.channel DirectChannel subscribe.

Prototype

@Override
    public boolean subscribe(MessageHandler handler) 

Source Link

Usage

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//  w  ww  . j ava2s  .co  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 testAutoBindDLQPartionedConsumerFirst() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
    properties.getExtension().setPrefix("bindertest.");
    properties.getExtension().setAutoBindDlq(true);
    properties.setMaxAttempts(1); // disable retry
    properties.setPartitioned(true);/*  w  w  w  .  j  a  v  a2 s . c o  m*/
    properties.setInstanceIndex(0);
    DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(properties));
    input0.setBeanName("test.input0DLQ");
    Binding<MessageChannel> input0Binding = binder.bindConsumer("partDLQ.0", "dlqPartGrp", input0, properties);
    Binding<MessageChannel> defaultConsumerBinding1 = binder.bindConsumer("partDLQ.0", "default",
            new QueueChannel(), properties);
    properties.setInstanceIndex(1);
    DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(properties));
    input1.setBeanName("test.input1DLQ");
    Binding<MessageChannel> input1Binding = binder.bindConsumer("partDLQ.0", "dlqPartGrp", input1, properties);
    Binding<MessageChannel> defaultConsumerBinding2 = binder.bindConsumer("partDLQ.0", "default",
            new QueueChannel(), properties);

    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setPrefix("bindertest.");
    producerProperties.getExtension().setAutoBindDlq(true);
    producerProperties.setPartitionKeyExtractorClass(PartitionTestSupport.class);
    producerProperties.setPartitionSelectorClass(PartitionTestSupport.class);
    producerProperties.setPartitionCount(2);
    BindingProperties bindingProperties = createProducerBindingProperties(producerProperties);
    DirectChannel output = createBindableChannel("output", bindingProperties);
    output.setBeanName("test.output");
    Binding<MessageChannel> outputBinding = binder.bindProducer("partDLQ.0", output, producerProperties);

    final CountDownLatch latch0 = new CountDownLatch(1);
    input0.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch0.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch0.countDown();
        }

    });

    final CountDownLatch latch1 = new CountDownLatch(1);
    input1.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch1.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch1.countDown();
        }

    });

    output.send(new GenericMessage<>(1));
    assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<>(0));
    assertThat(latch0.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<>(1));

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.setReceiveTimeout(10000);

    String streamDLQName = "bindertest.partDLQ.0.dlqPartGrp.dlq";

    org.springframework.amqp.core.Message received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedRoutingKey())
            .isEqualTo("bindertest.partDLQ.0.dlqPartGrp-1");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);

    output.send(new GenericMessage<>(0));
    received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedRoutingKey())
            .isEqualTo("bindertest.partDLQ.0.dlqPartGrp-0");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);

    input0Binding.unbind();
    input1Binding.unbind();
    defaultConsumerBinding1.unbind();
    defaultConsumerBinding2.unbind();
    outputBinding.unbind();
}

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

private void testAutoBindDLQPartionedConsumerFirstWithRepublishGuts(final boolean withRetry) throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
    properties.getExtension().setPrefix("bindertest.");
    properties.getExtension().setAutoBindDlq(true);
    properties.getExtension().setRepublishToDlq(true);
    properties.getExtension().setRepublishDeliveyMode(MessageDeliveryMode.NON_PERSISTENT);
    properties.setMaxAttempts(withRetry ? 2 : 1);
    properties.setPartitioned(true);/*from   w  w  w  .j a v a  2  s.  co  m*/
    properties.setInstanceIndex(0);
    DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(properties));
    input0.setBeanName("test.input0DLQ");
    Binding<MessageChannel> input0Binding = binder.bindConsumer("partPubDLQ.0", "dlqPartGrp", input0,
            properties);
    Binding<MessageChannel> defaultConsumerBinding1 = binder.bindConsumer("partPubDLQ.0", "default",
            new QueueChannel(), properties);
    properties.setInstanceIndex(1);
    DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(properties));
    input1.setBeanName("test.input1DLQ");
    Binding<MessageChannel> input1Binding = binder.bindConsumer("partPubDLQ.0", "dlqPartGrp", input1,
            properties);
    Binding<MessageChannel> defaultConsumerBinding2 = binder.bindConsumer("partPubDLQ.0", "default",
            new QueueChannel(), properties);

    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setPrefix("bindertest.");
    producerProperties.getExtension().setAutoBindDlq(true);
    producerProperties.setPartitionKeyExtractorClass(PartitionTestSupport.class);
    producerProperties.setPartitionSelectorClass(PartitionTestSupport.class);
    producerProperties.setPartitionCount(2);
    BindingProperties bindingProperties = createProducerBindingProperties(producerProperties);
    DirectChannel output = createBindableChannel("output", bindingProperties);
    output.setBeanName("test.output");
    Binding<MessageChannel> outputBinding = binder.bindProducer("partPubDLQ.0", output, producerProperties);

    final CountDownLatch latch0 = new CountDownLatch(1);
    input0.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch0.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch0.countDown();
        }

    });

    final CountDownLatch latch1 = new CountDownLatch(1);
    input1.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch1.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch1.countDown();
        }

    });

    ApplicationContext context = TestUtils.getPropertyValue(binder.getBinder(), "applicationContext",
            ApplicationContext.class);
    SubscribableChannel boundErrorChannel = context.getBean("bindertest.partPubDLQ.0.dlqPartGrp-0.errors",
            SubscribableChannel.class);
    SubscribableChannel globalErrorChannel = context.getBean("errorChannel", SubscribableChannel.class);
    final AtomicReference<Message<?>> boundErrorChannelMessage = new AtomicReference<>();
    final AtomicReference<Message<?>> globalErrorChannelMessage = new AtomicReference<>();
    final AtomicBoolean hasRecovererInCallStack = new AtomicBoolean(!withRetry);
    boundErrorChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            boundErrorChannelMessage.set(message);
            String stackTrace = Arrays.toString(new RuntimeException().getStackTrace());
            hasRecovererInCallStack.set(stackTrace.contains("ErrorMessageSendingRecoverer"));
        }

    });
    globalErrorChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            globalErrorChannelMessage.set(message);
        }

    });

    output.send(new GenericMessage<>(1));
    assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<>(0));
    assertThat(latch0.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<>(1));

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.setReceiveTimeout(10000);

    String streamDLQName = "bindertest.partPubDLQ.0.dlqPartGrp.dlq";

    org.springframework.amqp.core.Message received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getHeaders().get("x-original-routingKey"))
            .isEqualTo("partPubDLQ.0-1");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);
    assertThat(received.getMessageProperties().getReceivedDeliveryMode())
            .isEqualTo(MessageDeliveryMode.NON_PERSISTENT);

    output.send(new GenericMessage<>(0));
    received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getHeaders().get("x-original-routingKey"))
            .isEqualTo("partPubDLQ.0-0");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);

    // verify we got a message on the dedicated error channel and the global (via bridge)
    assertThat(boundErrorChannelMessage.get()).isNotNull();
    assertThat(globalErrorChannelMessage.get()).isNotNull();
    assertThat(hasRecovererInCallStack.get()).isEqualTo(withRetry);

    input0Binding.unbind();
    input1Binding.unbind();
    defaultConsumerBinding1.unbind();
    defaultConsumerBinding2.unbind();
    outputBinding.unbind();
}

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

@Test
public void testAutoBindDLQPartitionedProducerFirst() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedProducerProperties<RabbitProducerProperties> properties = createProducerProperties();

    properties.getExtension().setPrefix("bindertest.");
    properties.getExtension().setAutoBindDlq(true);
    properties.setRequiredGroups("dlqPartGrp");
    properties.setPartitionKeyExtractorClass(PartitionTestSupport.class);
    properties.setPartitionSelectorClass(PartitionTestSupport.class);
    properties.setPartitionCount(2);/*from   w ww. j  a  v  a  2  s . c  om*/
    DirectChannel output = createBindableChannel("output", createProducerBindingProperties(properties));
    output.setBeanName("test.output");
    Binding<MessageChannel> outputBinding = binder.bindProducer("partDLQ.1", output, properties);

    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix("bindertest.");
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.setMaxAttempts(1); // disable retry
    consumerProperties.setPartitioned(true);
    consumerProperties.setInstanceIndex(0);
    DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(consumerProperties));
    input0.setBeanName("test.input0DLQ");
    Binding<MessageChannel> input0Binding = binder.bindConsumer("partDLQ.1", "dlqPartGrp", input0,
            consumerProperties);
    Binding<MessageChannel> defaultConsumerBinding1 = binder.bindConsumer("partDLQ.1", "defaultConsumer",
            new QueueChannel(), consumerProperties);
    consumerProperties.setInstanceIndex(1);
    DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(consumerProperties));
    input1.setBeanName("test.input1DLQ");
    Binding<MessageChannel> input1Binding = binder.bindConsumer("partDLQ.1", "dlqPartGrp", input1,
            consumerProperties);
    Binding<MessageChannel> defaultConsumerBinding2 = binder.bindConsumer("partDLQ.1", "defaultConsumer",
            new QueueChannel(), consumerProperties);

    final CountDownLatch latch0 = new CountDownLatch(1);
    input0.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch0.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch0.countDown();
        }

    });

    final CountDownLatch latch1 = new CountDownLatch(1);
    input1.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch1.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch1.countDown();
        }

    });

    output.send(new GenericMessage<Integer>(1));
    assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<Integer>(0));
    assertThat(latch0.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<Integer>(1));

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.setReceiveTimeout(10000);

    String streamDLQName = "bindertest.partDLQ.1.dlqPartGrp.dlq";

    org.springframework.amqp.core.Message received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedRoutingKey())
            .isEqualTo("bindertest.partDLQ.1.dlqPartGrp-1");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);
    assertThat(received.getMessageProperties().getReceivedDeliveryMode())
            .isEqualTo(MessageDeliveryMode.PERSISTENT);

    output.send(new GenericMessage<Integer>(0));
    received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedRoutingKey())
            .isEqualTo("bindertest.partDLQ.1.dlqPartGrp-0");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);

    input0Binding.unbind();
    input1Binding.unbind();
    defaultConsumerBinding1.unbind();
    defaultConsumerBinding2.unbind();
    outputBinding.unbind();
}

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);// w  w  w  .jav a2  s  .c  om

    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.integration.aggregator.AggregatorTests.java

@Test
public void testAggPerf() throws InterruptedException, ExecutionException, TimeoutException {
    AggregatingMessageHandler handler = new AggregatingMessageHandler(
            new DefaultAggregatingMessageGroupProcessor());
    handler.setCorrelationStrategy(message -> "foo");
    handler.setReleaseStrategy(new MessageCountReleaseStrategy(60000));
    handler.setExpireGroupsUponCompletion(true);
    handler.setSendPartialResultOnExpiry(true);
    DirectChannel outputChannel = new DirectChannel();
    handler.setOutputChannel(outputChannel);

    final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>();
    outputChannel.subscribe(message -> {
        Collection<?> payload = (Collection<?>) message.getPayload();
        logger.warn("Received " + payload.size());
        resultFuture.complete(payload);//from   w  w w . j a va 2 s . c o m
    });

    SimpleMessageStore store = new SimpleMessageStore();

    SimpleMessageGroupFactory messageGroupFactory = new SimpleMessageGroupFactory(
            SimpleMessageGroupFactory.GroupType.BLOCKING_QUEUE);

    store.setMessageGroupFactory(messageGroupFactory);

    handler.setMessageStore(store);

    Message<?> message = new GenericMessage<String>("foo");
    StopWatch stopwatch = new StopWatch();
    stopwatch.start();
    for (int i = 0; i < 120000; i++) {
        if (i % 10000 == 0) {
            stopwatch.stop();
            logger.warn("Sent " + i + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
                    + stopwatch.getLastTaskTimeMillis() + "ms)");
            stopwatch.start();
        }
        handler.handleMessage(message);
    }
    stopwatch.stop();
    logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
            + stopwatch.getLastTaskTimeMillis() + "ms)");

    Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS);
    assertNotNull(result);
    assertEquals(60000, result.size());
}

From source file:org.springframework.integration.aggregator.AggregatorTests.java

@Test
public void testAggPerfDefaultPartial() throws InterruptedException, ExecutionException, TimeoutException {
    AggregatingMessageHandler handler = new AggregatingMessageHandler(
            new DefaultAggregatingMessageGroupProcessor());
    handler.setCorrelationStrategy(message -> "foo");
    handler.setReleasePartialSequences(true);
    DirectChannel outputChannel = new DirectChannel();
    handler.setOutputChannel(outputChannel);

    final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>();
    outputChannel.subscribe(message -> {
        Collection<?> payload = (Collection<?>) message.getPayload();
        logger.warn("Received " + payload.size());
        resultFuture.complete(payload);/*from w  w w  . j  a  v  a2  s .  c  o m*/
    });

    SimpleMessageStore store = new SimpleMessageStore();

    SimpleMessageGroupFactory messageGroupFactory = new SimpleMessageGroupFactory(
            SimpleMessageGroupFactory.GroupType.BLOCKING_QUEUE);

    store.setMessageGroupFactory(messageGroupFactory);

    handler.setMessageStore(store);

    StopWatch stopwatch = new StopWatch();
    stopwatch.start();
    for (int i = 0; i < 120000; i++) {
        if (i % 10000 == 0) {
            stopwatch.stop();
            logger.warn("Sent " + i + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
                    + stopwatch.getLastTaskTimeMillis() + "ms)");
            stopwatch.start();
        }
        handler.handleMessage(
                MessageBuilder.withPayload("foo").setSequenceSize(120000).setSequenceNumber(i + 1).build());
    }
    stopwatch.stop();
    logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
            + stopwatch.getLastTaskTimeMillis() + "ms)");

    Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS);
    assertNotNull(result);
    assertEquals(120000, result.size());
    assertThat(stopwatch.getTotalTimeSeconds(), lessThan(60.0)); // actually < 2.0, was many minutes
}

From source file:org.springframework.integration.amqp.outbound.AsyncAmqpGatewayTests.java

@Test
public void testConfirmsAndReturns() throws Exception {
    CachingConnectionFactory ccf = new CachingConnectionFactory("localhost");
    ccf.setPublisherConfirms(true);/*from w  w  w  . j  a va2 s  .  c  o m*/
    ccf.setPublisherReturns(true);
    RabbitTemplate template = new RabbitTemplate(ccf);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(ccf);
    container.setBeanName("replyContainer");
    container.setQueueNames("asyncRQ1");
    container.afterPropertiesSet();
    container.start();
    AsyncRabbitTemplate asyncTemplate = new AsyncRabbitTemplate(template, container);
    asyncTemplate.setEnableConfirms(true);
    asyncTemplate.setMandatory(true);

    SimpleMessageListenerContainer receiver = new SimpleMessageListenerContainer(ccf);
    receiver.setBeanName("receiver");
    receiver.setQueueNames("asyncQ1");
    final CountDownLatch waitForAckBeforeReplying = new CountDownLatch(1);
    MessageListenerAdapter messageListener = new MessageListenerAdapter(
            (ReplyingMessageListener<String, String>) foo -> {
                try {
                    waitForAckBeforeReplying.await(10, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                return foo.toUpperCase();
            });
    receiver.setMessageListener(messageListener);
    receiver.afterPropertiesSet();
    receiver.start();

    AsyncAmqpOutboundGateway gateway = new AsyncAmqpOutboundGateway(asyncTemplate);
    Log logger = spy(TestUtils.getPropertyValue(gateway, "logger", Log.class));
    given(logger.isDebugEnabled()).willReturn(true);
    final CountDownLatch replyTimeoutLatch = new CountDownLatch(1);
    willAnswer(invocation -> {
        invocation.callRealMethod();
        replyTimeoutLatch.countDown();
        return null;
    }).given(logger).debug(startsWith("Reply not required and async timeout for"));
    new DirectFieldAccessor(gateway).setPropertyValue("logger", logger);
    QueueChannel outputChannel = new QueueChannel();
    outputChannel.setBeanName("output");
    QueueChannel returnChannel = new QueueChannel();
    returnChannel.setBeanName("returns");
    QueueChannel ackChannel = new QueueChannel();
    ackChannel.setBeanName("acks");
    QueueChannel errorChannel = new QueueChannel();
    errorChannel.setBeanName("errors");
    gateway.setOutputChannel(outputChannel);
    gateway.setReturnChannel(returnChannel);
    gateway.setConfirmAckChannel(ackChannel);
    gateway.setConfirmNackChannel(ackChannel);
    gateway.setConfirmCorrelationExpressionString("#this");
    gateway.setExchangeName("");
    gateway.setRoutingKey("asyncQ1");
    gateway.setBeanFactory(mock(BeanFactory.class));
    gateway.afterPropertiesSet();
    gateway.start();

    Message<?> message = MessageBuilder.withPayload("foo").setErrorChannel(errorChannel).build();

    gateway.handleMessage(message);

    Message<?> ack = ackChannel.receive(10000);
    assertNotNull(ack);
    assertEquals("foo", ack.getPayload());
    assertEquals(true, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM));
    waitForAckBeforeReplying.countDown();

    Message<?> received = outputChannel.receive(10000);
    assertNotNull(received);
    assertEquals("FOO", received.getPayload());

    // timeout tests
    asyncTemplate.setReceiveTimeout(10);

    receiver.setMessageListener(message1 -> {
    });
    // reply timeout with no requiresReply
    message = MessageBuilder.withPayload("bar").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);
    assertTrue(replyTimeoutLatch.await(10, TimeUnit.SECONDS));

    // reply timeout with requiresReply
    gateway.setRequiresReply(true);
    message = MessageBuilder.withPayload("baz").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);

    received = errorChannel.receive(10000);
    assertThat(received, instanceOf(ErrorMessage.class));
    ErrorMessage error = (ErrorMessage) received;
    assertThat(error.getPayload(), instanceOf(MessagingException.class));
    assertThat(error.getPayload().getCause(), instanceOf(AmqpReplyTimeoutException.class));
    asyncTemplate.setReceiveTimeout(30000);
    receiver.setMessageListener(messageListener);

    // error on sending result
    DirectChannel errorForce = new DirectChannel();
    errorForce.setBeanName("errorForce");
    errorForce.subscribe(message1 -> {
        throw new RuntimeException("intentional");
    });
    gateway.setOutputChannel(errorForce);
    message = MessageBuilder.withPayload("qux").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);
    received = errorChannel.receive(10000);
    assertThat(received, instanceOf(ErrorMessage.class));
    error = (ErrorMessage) received;
    assertThat(error.getPayload(), instanceOf(MessagingException.class));
    assertEquals("QUX", ((MessagingException) error.getPayload()).getFailedMessage().getPayload());

    gateway.setRoutingKey(UUID.randomUUID().toString());
    message = MessageBuilder.withPayload("fiz").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);
    Message<?> returned = returnChannel.receive(10000);
    assertNotNull(returned);
    assertEquals("fiz", returned.getPayload());
    ackChannel.receive(10000);
    ackChannel.purge(null);

    asyncTemplate = mock(AsyncRabbitTemplate.class);
    RabbitMessageFuture future = asyncTemplate.new RabbitMessageFuture(null, null);
    willReturn(future).given(asyncTemplate).sendAndReceive(anyString(), anyString(),
            any(org.springframework.amqp.core.Message.class));
    DirectFieldAccessor dfa = new DirectFieldAccessor(future);
    dfa.setPropertyValue("nackCause", "nacknack");
    SettableListenableFuture<Boolean> confirmFuture = new SettableListenableFuture<Boolean>();
    confirmFuture.set(false);
    dfa.setPropertyValue("confirm", confirmFuture);
    new DirectFieldAccessor(gateway).setPropertyValue("template", asyncTemplate);

    message = MessageBuilder.withPayload("buz").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);

    ack = ackChannel.receive(10000);
    assertNotNull(ack);
    assertEquals("buz", ack.getPayload());
    assertEquals("nacknack", ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM_NACK_CAUSE));
    assertEquals(false, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM));

    asyncTemplate.stop();
    receiver.stop();
    ccf.destroy();
}

From source file:org.springframework.integration.channel.DirectChannelTests.java

@Test
public void testSend() {
    DirectChannel channel = new DirectChannel();
    Log logger = spy(TestUtils.getPropertyValue(channel, "logger", Log.class));
    when(logger.isDebugEnabled()).thenReturn(true);
    new DirectFieldAccessor(channel).setPropertyValue("logger", logger);
    ThreadNameExtractingTestTarget target = new ThreadNameExtractingTestTarget();
    channel.subscribe(target);
    GenericMessage<String> message = new GenericMessage<String>("test");
    assertTrue(channel.send(message));//from   w w  w . j  ava 2s.  co  m
    assertEquals(Thread.currentThread().getName(), target.threadName);
    DirectFieldAccessor channelAccessor = new DirectFieldAccessor(channel);
    UnicastingDispatcher dispatcher = (UnicastingDispatcher) channelAccessor.getPropertyValue("dispatcher");
    DirectFieldAccessor dispatcherAccessor = new DirectFieldAccessor(dispatcher);
    Object loadBalancingStrategy = dispatcherAccessor.getPropertyValue("loadBalancingStrategy");
    assertTrue(loadBalancingStrategy instanceof RoundRobinLoadBalancingStrategy);
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(logger, times(2)).debug(captor.capture());
    List<String> logs = captor.getAllValues();
    assertEquals(2, logs.size());
    assertThat(logs.get(0), startsWith("preSend"));
    assertThat(logs.get(1), startsWith("postSend"));
}

From source file:org.springframework.integration.channel.DirectChannelTests.java

@Test
public void testSendPerfOneHandler() {
    /*/*w  w w  . ja  v  a 2s .com*/
     *  INT-3308 - used to run 12 million/sec
     *  1. optimize for single handler 20 million/sec
     *  2. Don't iterate over empty datatypes 23 million/sec
     *  3. Don't iterate over empty interceptors 31 million/sec
     *  4. Move single handler optimization to dispatcher 34 million/sec
     *
     *  29 million per second with increment counter in the handler
     */
    DirectChannel channel = new DirectChannel();
    final AtomicInteger count = new AtomicInteger();
    channel.subscribe(message -> count.incrementAndGet());
    GenericMessage<String> message = new GenericMessage<String>("test");
    assertTrue(channel.send(message));
    for (int i = 0; i < 10000000; i++) {
        channel.send(message);
    }
}