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

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

Introduction

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

Prototype

@Override
public boolean send(Message<?> message) 

Source Link

Document

Send a message on this channel.

Usage

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

@Test
public void testProducerProperties() throws Exception {
    RabbitTestBinder binder = getBinder();
    Binding<MessageChannel> producerBinding = binder.bindProducer("props.0",
            createBindableChannel("input", new BindingProperties()), createProducerProperties());
    Lifecycle endpoint = extractEndpoint(producerBinding);
    MessageDeliveryMode mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode",
            MessageDeliveryMode.class);
    assertThat(mode).isEqualTo(MessageDeliveryMode.PERSISTENT);
    List<?> requestHeaders = TestUtils.getPropertyValue(endpoint, "headerMapper.requestHeaderMatcher.matchers",
            List.class);
    assertThat(requestHeaders).hasSize(2);
    producerBinding.unbind();//from   ww  w .j av  a  2 s  .co  m
    assertThat(endpoint.isRunning()).isFalse();
    assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", Boolean.class)).isFalse();

    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setPrefix("foo.");
    producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
    producerProperties.getExtension().setHeaderPatterns(new String[] { "foo" });
    producerProperties.setPartitionKeyExpression(spelExpressionParser.parseExpression("'foo'"));
    producerProperties.setPartitionKeyExtractorClass(TestPartitionKeyExtractorClass.class);
    producerProperties.setPartitionSelectorExpression(spelExpressionParser.parseExpression("0"));
    producerProperties.setPartitionSelectorClass(TestPartitionSelectorClass.class);
    producerProperties.setPartitionCount(1);
    producerProperties.getExtension().setTransacted(true);
    producerProperties.getExtension().setDelayExpression("42");
    producerProperties.setRequiredGroups("prodPropsRequired");

    BindingProperties producerBindingProperties = createProducerBindingProperties(producerProperties);
    DirectChannel channel = createBindableChannel("output", producerBindingProperties);
    producerBinding = binder.bindProducer("props.0", channel, producerProperties);
    endpoint = extractEndpoint(producerBinding);
    assertThat(getEndpointRouting(endpoint))
            .isEqualTo("'props.0-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
    assertThat(
            TestUtils.getPropertyValue(endpoint, "delayExpression", SpelExpression.class).getExpressionString())
                    .isEqualTo("42");
    mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode", MessageDeliveryMode.class);
    assertThat(mode).isEqualTo(MessageDeliveryMode.NON_PERSISTENT);
    assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", Boolean.class)).isTrue();
    verifyFooRequestProducer(endpoint);
    channel.send(new GenericMessage<>("foo"));
    org.springframework.amqp.core.Message received = new RabbitTemplate(this.rabbitAvailableRule.getResource())
            .receive("foo.props.0.prodPropsRequired-0", 10_000);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedDelay()).isEqualTo(42);

    producerBinding.unbind();
    assertThat(endpoint.isRunning()).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);/*from  w  w  w .  j  av  a 2 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 va2 s .c  o  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);// ww  w  .ja v  a 2  s.  c o  m
    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

@SuppressWarnings("unchecked")
@Test/* w w  w  .  j a va2s.com*/
public void testBatchingAndCompression() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
    producerProperties.getExtension().setBatchingEnabled(true);
    producerProperties.getExtension().setBatchSize(2);
    producerProperties.getExtension().setBatchBufferLimit(100000);
    producerProperties.getExtension().setBatchTimeout(30000);
    producerProperties.getExtension().setCompress(true);
    producerProperties.setRequiredGroups("default");

    DirectChannel output = createBindableChannel("input", createProducerBindingProperties(producerProperties));
    output.setBeanName("batchingProducer");
    Binding<MessageChannel> producerBinding = binder.bindProducer("batching.0", output, producerProperties);

    Log logger = spy(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor.logger", Log.class));
    new DirectFieldAccessor(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor"))
            .setPropertyValue("logger", logger);
    when(logger.isTraceEnabled()).thenReturn(true);

    assertThat(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor.level"))
            .isEqualTo(Deflater.BEST_SPEED);

    output.send(new GenericMessage<>("foo".getBytes()));
    output.send(new GenericMessage<>("bar".getBytes()));

    Object out = spyOn("batching.0.default").receive(false);
    assertThat(out).isInstanceOf(byte[].class);
    assertThat(new String((byte[]) out)).isEqualTo("\u0000\u0000\u0000\u0003foo\u0000\u0000\u0000\u0003bar");

    ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
    verify(logger).trace(captor.capture());
    assertThat(captor.getValue().toString()).contains(("Compressed 14 to "));

    QueueChannel input = new QueueChannel();
    input.setBeanName("batchingConsumer");
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("batching.0", "test", input,
            createConsumerProperties());

    output.send(new GenericMessage<>("foo".getBytes()));
    output.send(new GenericMessage<>("bar".getBytes()));

    Message<byte[]> in = (Message<byte[]>) input.receive(10000);
    assertThat(in).isNotNull();
    assertThat(new String(in.getPayload())).isEqualTo("foo");
    in = (Message<byte[]>) input.receive(10000);
    assertThat(in).isNotNull();
    assertThat(new String(in.getPayload())).isEqualTo("bar");
    assertThat(in.getHeaders().get(AmqpHeaders.DELIVERY_MODE)).isNull();

    producerBinding.unbind();
    consumerBinding.unbind();
}

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);/* w ww . j a v a  2s . c o  m*/
    GenericMessage<String> message = new GenericMessage<String>("test");
    assertTrue(channel.send(message));
    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() {
    /*/*from  w w  w .j av  a 2s .co  m*/
     *  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);
    }
}

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

@Test
public void testSendPerfTwoHandlers() {
    /*/*w ww.  ja v a 2  s.c  o m*/
     *  INT-3308 - used to run 6.4 million/sec
     *  1. Skip empty iterators as above 7.2 million/sec
     *  2. optimize for single handler 6.7 million/sec (small overhead added)
     *  3. remove LB rwlock from UnicastingDispatcher 7.2 million/sec
     *  4. Move single handler optimization to dispatcher 7.3 million/sec
     */
    DirectChannel channel = new DirectChannel();
    final AtomicInteger count1 = new AtomicInteger();
    final AtomicInteger count2 = new AtomicInteger();
    channel.subscribe(message -> count1.incrementAndGet());
    channel.subscribe(message -> count2.getAndIncrement());
    GenericMessage<String> message = new GenericMessage<String>("test");
    assertTrue(channel.send(message));
    for (int i = 0; i < 10000000; i++) {
        channel.send(message);
    }
    assertEquals(5000001, count1.get());
    assertEquals(5000000, count2.get());
}

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

@Test
public void testSendInSeparateThread() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    final DirectChannel channel = new DirectChannel();
    ThreadNameExtractingTestTarget target = new ThreadNameExtractingTestTarget(latch);
    channel.subscribe(target);//  www .  ja v  a2s  . co  m
    final GenericMessage<String> message = new GenericMessage<String>("test");
    new Thread((Runnable) () -> channel.send(message), "test-thread").start();
    latch.await(1000, TimeUnit.MILLISECONDS);
    assertEquals("test-thread", target.threadName);
}

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

@Test
public void testSendAndReceiveBad() throws Exception {
    MessageBus messageBus = getMessageBus();
    DirectChannel moduleOutputChannel = new DirectChannel();
    DirectChannel moduleInputChannel = new DirectChannel();
    messageBus.bindProducer("bad.0", moduleOutputChannel, null);
    messageBus.bindConsumer("bad.0", moduleInputChannel, null);
    Message<?> message = MessageBuilder.withPayload("bad").setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar")
            .build();//from  w w  w .  j  a va  2 s .  co  m
    final CountDownLatch latch = new CountDownLatch(3);
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            latch.countDown();
            throw new RuntimeException("bad");
        }
    });
    moduleOutputChannel.send(message);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    messageBus.unbindConsumers("bad.0");
    messageBus.unbindProducers("bad.0");
}