List of usage examples for org.springframework.integration.channel DirectChannel DirectChannel
public DirectChannel()
From source file:org.springframework.integration.aggregator.AggregatorTests.java
@Test public void testCustomAggPerf() throws InterruptedException, ExecutionException, TimeoutException { class CustomHandler extends AbstractMessageHandler { // custom aggregator, only handles a single correlation private final ReentrantLock lock = new ReentrantLock(); private final Collection<Message<?>> messages = new ArrayList<Message<?>>(60000); private final MessageChannel outputChannel; private CustomHandler(MessageChannel outputChannel) { this.outputChannel = outputChannel; }//www . j ava 2 s.c o m @Override public void handleMessageInternal(Message<?> requestMessage) { lock.lock(); try { this.messages.add(requestMessage); if (this.messages.size() == 60000) { List<Object> payloads = new ArrayList<Object>(this.messages.size()); for (Message<?> message : this.messages) { payloads.add(message.getPayload()); } this.messages.clear(); outputChannel.send(getMessageBuilderFactory().withPayload(payloads) .copyHeaders(requestMessage.getHeaders()).build()); } } finally { lock.unlock(); } } } DirectChannel outputChannel = new DirectChannel(); CustomHandler handler = new CustomHandler(outputChannel); final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>(); outputChannel.subscribe(message -> { Collection<?> payload = (Collection<?>) message.getPayload(); logger.warn("Received " + payload.size()); resultFuture.complete(payload); }); 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.amqp.outbound.AsyncAmqpGatewayTests.java
@Test public void testConfirmsAndReturns() throws Exception { CachingConnectionFactory ccf = new CachingConnectionFactory("localhost"); ccf.setPublisherConfirms(true);/*from w w w .j ava 2 s. com*/ 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);//from w ww .j av a2 s . co 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 www.ja va 2s . c o 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() { /*/*from w ww . j a v a 2s . c om*/ * 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);/*from w w w. j a v a 2 s . c o 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.integration.channel.P2pChannelTests.java
@Test public void testDirectChannelLoggingWithMoreThenOneSubscriber() { final DirectChannel channel = new DirectChannel(); channel.setBeanName("directChannel"); verifySubscriptions(channel);// w ww .j a v a2s . c om }
From source file:org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.java
protected AbstractEndpoint createEndpoint(MessageHandler handler, Method method, List<Annotation> annotations) { AbstractEndpoint endpoint = null;//from w w w.j a va 2 s . c o m String inputChannelName = MessagingAnnotationUtils.resolveAttribute(annotations, getInputChannelAttribute(), String.class); if (StringUtils.hasText(inputChannelName)) { MessageChannel inputChannel; try { inputChannel = this.channelResolver.resolveDestination(inputChannelName); } catch (DestinationResolutionException e) { if (e.getCause() instanceof NoSuchBeanDefinitionException) { inputChannel = new DirectChannel(); this.beanFactory.registerSingleton(inputChannelName, inputChannel); inputChannel = (MessageChannel) this.beanFactory.initializeBean(inputChannel, inputChannelName); } else { throw e; } } Assert.notNull(inputChannel, "failed to resolve inputChannel '" + inputChannelName + "'"); endpoint = doCreateEndpoint(handler, inputChannel, annotations); } return endpoint; }
From source file:org.springframework.integration.handler.AsyncHandlerTests.java
@Test public void testGateway() throws Exception { this.whichTest = 0; GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean(Foo.class); gpfb.setBeanFactory(mock(BeanFactory.class)); DirectChannel input = new DirectChannel(); gpfb.setDefaultRequestChannel(input); gpfb.setDefaultReplyTimeout(10000L); gpfb.afterPropertiesSet();//from w ww . j a v a 2 s .c om Foo foo = (Foo) gpfb.getObject(); this.handler.setOutputChannel(null); EventDrivenConsumer consumer = new EventDrivenConsumer(input, this.handler); consumer.afterPropertiesSet(); consumer.start(); this.latch.countDown(); String result = foo.exchange("foo"); assertEquals("reply", result); }
From source file:org.springframework.integration.handler.AsyncHandlerTests.java
@Test public void testGatewayWithException() throws Exception { this.whichTest = 0; GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean(Foo.class); gpfb.setBeanFactory(mock(BeanFactory.class)); DirectChannel input = new DirectChannel(); gpfb.setDefaultRequestChannel(input); gpfb.setDefaultReplyTimeout(10000L); gpfb.afterPropertiesSet();// ww w .j a v a 2s . com Foo foo = (Foo) gpfb.getObject(); this.handler.setOutputChannel(null); EventDrivenConsumer consumer = new EventDrivenConsumer(input, this.handler); consumer.afterPropertiesSet(); consumer.start(); this.latch.countDown(); try { foo.exchange("foo"); } catch (MessagingException e) { assertThat(e.getClass().getSimpleName(), equalTo("RuntimeException")); assertThat(e.getMessage(), equalTo("foo")); } }