Java Code Examples for org.springframework.integration.channel.DirectChannel#send()

The following examples show how to use org.springframework.integration.channel.DirectChannel#send() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PartitionCapableBinderTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testOneRequiredGroup() throws Exception {
	B binder = getBinder();
	PP producerProperties = createProducerProperties();
	DirectChannel output = createBindableChannel("output",
			createProducerBindingProperties(producerProperties));

	String testDestination = "testDestination"
			+ UUID.randomUUID().toString().replace("-", "");

	producerProperties.setRequiredGroups("test1");
	Binding<MessageChannel> producerBinding = binder.bindProducer(testDestination,
			output, producerProperties);

	String testPayload = "foo-" + UUID.randomUUID().toString();
	output.send(MessageBuilder.withPayload(testPayload)
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN)
			.build());

	QueueChannel inbound1 = new QueueChannel();
	Binding<MessageChannel> consumerBinding = binder.bindConsumer(testDestination,
			"test1", inbound1, createConsumerProperties());

	Message<?> receivedMessage1 = receive(inbound1);
	assertThat(receivedMessage1).isNotNull();
	assertThat(new String((byte[]) receivedMessage1.getPayload()))
			.isEqualTo(testPayload);

	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example 2
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCustomPartitionCountOverridesPartitioningIfLarger() throws Exception {
	byte[] testPayload = new byte[2048];
	Arrays.fill(testPayload, (byte) 65);
	KafkaBinderConfigurationProperties binderConfiguration = createConfigurationProperties();
	binderConfiguration.setMinPartitionCount(4);
	Binder binder = getBinder(binderConfiguration);

	QueueChannel moduleInputChannel = new QueueChannel();
	ExtendedProducerProperties<KafkaProducerProperties> producerProperties = createProducerProperties();
	producerProperties.setPartitionCount(5);
	producerProperties.setPartitionKeyExpression(
			spelExpressionParser.parseExpression("payload"));
	DirectChannel moduleOutputChannel = createBindableChannel("output",
			createProducerBindingProperties(producerProperties));
	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();
	long uniqueBindingId = System.currentTimeMillis();
	Binding<MessageChannel> producerBinding = binder.bindProducer(
			"foo" + uniqueBindingId + ".0", moduleOutputChannel, producerProperties);
	Binding<MessageChannel> consumerBinding = binder.bindConsumer(
			"foo" + uniqueBindingId + ".0", null, moduleInputChannel,
			consumerProperties);
	Message<?> message = org.springframework.integration.support.MessageBuilder
			.withPayload(testPayload).build();
	// Let the consumer actually bind to the producer before sending a msg
	binderBindUnbindLatency();
	moduleOutputChannel.send(message);
	Message<?> inbound = receive(moduleInputChannel);
	assertThat(inbound).isNotNull();
	assertThat((byte[]) inbound.getPayload()).containsExactly(testPayload);
	assertThat(partitionSize("foo" + uniqueBindingId + ".0")).isEqualTo(5);
	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example 3
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCustomPartitionCountDoesNotOverridePartitioningIfSmaller()
		throws Exception {
	byte[] testPayload = new byte[2048];
	Arrays.fill(testPayload, (byte) 65);
	KafkaBinderConfigurationProperties binderConfiguration = createConfigurationProperties();
	binderConfiguration.setMinPartitionCount(6);
	Binder binder = getBinder(binderConfiguration);
	QueueChannel moduleInputChannel = new QueueChannel();
	ExtendedProducerProperties<KafkaProducerProperties> producerProperties = createProducerProperties();
	producerProperties.setPartitionCount(5);
	producerProperties.setPartitionKeyExpression(
			spelExpressionParser.parseExpression("payload"));
	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();
	long uniqueBindingId = System.currentTimeMillis();
	DirectChannel moduleOutputChannel = createBindableChannel("output",
			createProducerBindingProperties(producerProperties));
	Binding<MessageChannel> producerBinding = binder.bindProducer(
			"foo" + uniqueBindingId + ".0", moduleOutputChannel, producerProperties);
	Binding<MessageChannel> consumerBinding = binder.bindConsumer(
			"foo" + uniqueBindingId + ".0", null, moduleInputChannel,
			consumerProperties);
	Thread.sleep(1000);
	Message<?> message = org.springframework.integration.support.MessageBuilder
			.withPayload(testPayload).build();
	// Let the consumer actually bind to the producer before sending a msg
	binderBindUnbindLatency();
	moduleOutputChannel.send(message);
	Message<?> inbound = receive(moduleInputChannel);
	assertThat(inbound).isNotNull();
	assertThat((byte[]) inbound.getPayload()).containsExactly(testPayload);

	assertThat(partitionSize("foo" + uniqueBindingId + ".0")).isEqualTo(6);
	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example 4
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testPartitionedNative() throws Exception {
	Binder binder = getBinder();
	ExtendedProducerProperties<KafkaProducerProperties> properties = createProducerProperties();
	properties.setPartitionCount(6);

	DirectChannel output = createBindableChannel("output",
			createProducerBindingProperties(properties));
	output.setBeanName("test.output");
	Binding<MessageChannel> outputBinding = binder.bindProducer("partNative.raw.0",
			output, properties);

	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();
	QueueChannel input0 = new QueueChannel();
	input0.setBeanName("test.inputNative");
	Binding<MessageChannel> inputBinding = binder.bindConsumer("partNative.raw.0",
			"test", input0, consumerProperties);

	output.send(new GenericMessage<>("foo".getBytes(),
			Collections.singletonMap(KafkaHeaders.PARTITION_ID, 5)));

	Message<?> received = receive(input0);
	assertThat(received).isNotNull();

	assertThat(received.getPayload()).isEqualTo("foo".getBytes());
	assertThat(received.getHeaders().get(KafkaHeaders.RECEIVED_PARTITION_ID))
			.isEqualTo(5);

	inputBinding.unbind();
	outputBinding.unbind();
}
 
Example 5
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomBatchingStrategy() throws Exception {
	RabbitTestBinder binder = getBinder();
	ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
	producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
	producerProperties.getExtension().setBatchingEnabled(true);
	producerProperties.getExtension().setBatchingStrategyBeanName("testCustomBatchingStrategy");
	producerProperties.setRequiredGroups("default");

	ConfigurableListableBeanFactory beanFactory = binder.getApplicationContext().getBeanFactory();
	beanFactory.registerSingleton("testCustomBatchingStrategy", new TestBatchingStrategy());

	DirectChannel output = createBindableChannel("output", 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<>("0".getBytes()));
	output.send(new GenericMessage<>("1".getBytes()));
	output.send(new GenericMessage<>("2".getBytes()));
	output.send(new GenericMessage<>("3".getBytes()));
	output.send(new GenericMessage<>("4".getBytes()));

	Object out = spyOn("batching.0.default").receive(false);
	assertThat(out).isInstanceOf(byte[].class);
	assertThat(new String((byte[]) out)).isEqualTo("0\u0000\n1\u0000\n2\u0000\n3\u0000\n4\u0000\n");

	producerBinding.unbind();
}
 
Example 6
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCustomPartitionCountOverridesDefaultIfLarger() throws Exception {
	byte[] testPayload = new byte[2048];
	Arrays.fill(testPayload, (byte) 65);
	KafkaBinderConfigurationProperties binderConfiguration = createConfigurationProperties();
	binderConfiguration.setMinPartitionCount(10);
	Binder binder = getBinder(binderConfiguration);
	QueueChannel moduleInputChannel = new QueueChannel();
	ExtendedProducerProperties<KafkaProducerProperties> producerProperties = createProducerProperties();
	producerProperties.setPartitionCount(10);
	producerProperties.setPartitionKeyExpression(new LiteralExpression("foo"));

	DirectChannel moduleOutputChannel = createBindableChannel("output",
			createProducerBindingProperties(producerProperties));

	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();
	long uniqueBindingId = System.currentTimeMillis();
	Binding<MessageChannel> producerBinding = binder.bindProducer(
			"foo" + uniqueBindingId + ".0", moduleOutputChannel, producerProperties);
	Binding<MessageChannel> consumerBinding = binder.bindConsumer(
			"foo" + uniqueBindingId + ".0", null, moduleInputChannel,
			consumerProperties);
	Message<?> message = org.springframework.integration.support.MessageBuilder
			.withPayload(testPayload).build();
	// Let the consumer actually bind to the producer before sending a msg
	binderBindUnbindLatency();
	moduleOutputChannel.send(message);
	Message<?> inbound = receive(moduleInputChannel);
	assertThat(inbound).isNotNull();
	assertThat((byte[]) inbound.getPayload()).containsExactly(testPayload);

	assertThat(partitionSize("foo" + uniqueBindingId + ".0")).isEqualTo(10);
	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example 7
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testPartitionedModuleSpELWithRawMode() throws Exception {
	Binder binder = getBinder();
	ExtendedProducerProperties<KafkaProducerProperties> properties = createProducerProperties();
	properties.setPartitionKeyExpression(
			spelExpressionParser.parseExpression("payload[0]"));
	properties.setPartitionSelectorExpression(
			spelExpressionParser.parseExpression("hashCode()"));
	properties.setPartitionCount(6);
	properties.setHeaderMode(HeaderMode.none);

	DirectChannel output = createBindableChannel("output",
			createProducerBindingProperties(properties));
	output.setBeanName("test.output");
	Binding<MessageChannel> outputBinding = binder.bindProducer("part.raw.0", output,
			properties);
	try {
		Object endpoint = extractEndpoint(outputBinding);
		assertThat(getEndpointRouting(endpoint))
				.contains(getExpectedRoutingBaseDestination("part.raw.0", "test")
						+ "-' + headers['partition']");
	}
	catch (UnsupportedOperationException ignored) {
	}

	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();
	consumerProperties.setConcurrency(2);
	consumerProperties.setInstanceIndex(0);
	consumerProperties.setInstanceCount(3);
	consumerProperties.setPartitioned(true);
	consumerProperties.setHeaderMode(HeaderMode.none);
	consumerProperties.getExtension().setAutoRebalanceEnabled(false);
	QueueChannel input0 = new QueueChannel();
	input0.setBeanName("test.input0S");
	Binding<MessageChannel> input0Binding = binder.bindConsumer("part.raw.0", "test",
			input0, consumerProperties);
	consumerProperties.setInstanceIndex(1);
	QueueChannel input1 = new QueueChannel();
	input1.setBeanName("test.input1S");
	Binding<MessageChannel> input1Binding = binder.bindConsumer("part.raw.0", "test",
			input1, consumerProperties);
	consumerProperties.setInstanceIndex(2);
	QueueChannel input2 = new QueueChannel();
	input2.setBeanName("test.input2S");
	Binding<MessageChannel> input2Binding = binder.bindConsumer("part.raw.0", "test",
			input2, consumerProperties);

	Message<byte[]> message2 = org.springframework.integration.support.MessageBuilder
			.withPayload(new byte[] { 2 })
			.setHeader(IntegrationMessageHeaderAccessor.CORRELATION_ID,
					"kafkaBinderTestCommonsDelegate")
			.setHeader(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, 42)
			.setHeader(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE, 43).build();
	output.send(message2);
	output.send(new GenericMessage<>(new byte[] { 1 }));
	output.send(new GenericMessage<>(new byte[] { 0 }));
	Message<?> receive0 = receive(input0);
	assertThat(receive0).isNotNull();
	Message<?> receive1 = receive(input1);
	assertThat(receive1).isNotNull();
	Message<?> receive2 = receive(input2);
	assertThat(receive2).isNotNull();
	assertThat(Arrays.asList(((byte[]) receive0.getPayload())[0],
			((byte[]) receive1.getPayload())[0], ((byte[]) receive2.getPayload())[0]))
					.containsExactlyInAnyOrder((byte) 0, (byte) 1, (byte) 2);
	input0Binding.unbind();
	input1Binding.unbind();
	input2Binding.unbind();
	outputBinding.unbind();
}
 
Example 8
Source File: KinesisBinderTests.java    From spring-cloud-stream-binder-aws-kinesis with Apache License 2.0 4 votes vote down vote up
@Test
@Override
@SuppressWarnings("unchecked")
public void testAnonymousGroup() throws Exception {
	KinesisTestBinder binder = getBinder();
	ExtendedProducerProperties<KinesisProducerProperties> producerProperties = createProducerProperties();
	DirectChannel output = createBindableChannel("output",
			createProducerBindingProperties(producerProperties));

	Binding<MessageChannel> producerBinding = binder.bindProducer(
			String.format("defaultGroup%s0", getDestinationNameDelimiter()), output,
			producerProperties);

	ExtendedConsumerProperties<KinesisConsumerProperties> consumerProperties = createConsumerProperties();
	consumerProperties.setConcurrency(2);
	consumerProperties.setInstanceCount(3);
	consumerProperties.setInstanceIndex(0);

	QueueChannel input1 = new QueueChannel();
	Binding<MessageChannel> binding1 = binder.bindConsumer(
			String.format("defaultGroup%s0", getDestinationNameDelimiter()), null,
			input1, consumerProperties);

	consumerProperties.setInstanceIndex(1);

	QueueChannel input2 = new QueueChannel();
	Binding<MessageChannel> binding2 = binder.bindConsumer(
			String.format("defaultGroup%s0", getDestinationNameDelimiter()), null,
			input2, consumerProperties);

	String testPayload1 = "foo-" + UUID.randomUUID().toString();
	output.send(MessageBuilder.withPayload(testPayload1)
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN)
			.build());

	Message<byte[]> receivedMessage1 = (Message<byte[]>) receive(input1);
	assertThat(receivedMessage1).isNotNull();
	assertThat(new String(receivedMessage1.getPayload())).isEqualTo(testPayload1);

	Message<byte[]> receivedMessage2 = (Message<byte[]>) receive(input2);
	assertThat(receivedMessage2).isNotNull();
	assertThat(new String(receivedMessage2.getPayload())).isEqualTo(testPayload1);

	binding2.unbind();

	String testPayload2 = "foo-" + UUID.randomUUID().toString();
	output.send(MessageBuilder.withPayload(testPayload2)
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN)
			.build());

	binding2 = binder.bindConsumer(
			String.format("defaultGroup%s0", getDestinationNameDelimiter()), null,
			input2, consumerProperties);
	String testPayload3 = "foo-" + UUID.randomUUID().toString();
	output.send(MessageBuilder.withPayload(testPayload3)
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN)
			.build());

	receivedMessage1 = (Message<byte[]>) receive(input1);
	assertThat(receivedMessage1).isNotNull();
	assertThat(new String(receivedMessage1.getPayload())).isEqualTo(testPayload2);
	receivedMessage1 = (Message<byte[]>) receive(input1);
	assertThat(receivedMessage1).isNotNull();
	assertThat(new String(receivedMessage1.getPayload())).isNotNull();

	receivedMessage2 = (Message<byte[]>) receive(input2);
	assertThat(receivedMessage2).isNotNull();
	assertThat(new String(receivedMessage2.getPayload())).isEqualTo(testPayload1);

	receivedMessage2 = (Message<byte[]>) receive(input2);
	assertThat(receivedMessage2).isNotNull();
	assertThat(new String(receivedMessage2.getPayload())).isEqualTo(testPayload2);

	receivedMessage2 = (Message<byte[]>) receive(input2);
	assertThat(receivedMessage2).isNotNull();
	assertThat(new String(receivedMessage2.getPayload())).isEqualTo(testPayload3);

	producerBinding.unbind();
	binding1.unbind();
	binding2.unbind();
}
 
Example 9
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testManualAckSucceedsWhenAutoCommitOffsetIsTurnedOff() throws Exception {
	Binder binder = getBinder();

	DirectChannel moduleOutputChannel = createBindableChannel("output",
			createProducerBindingProperties(createProducerProperties()));
	QueueChannel moduleInputChannel = new QueueChannel();

	Binding<MessageChannel> producerBinding = binder.bindProducer(
			"testManualAckSucceedsWhenAutoCommitOffsetIsTurnedOff",
			moduleOutputChannel, createProducerProperties());

	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();
	consumerProperties.getExtension().setAutoCommitOffset(false);

	Binding<MessageChannel> consumerBinding = binder.bindConsumer(
			"testManualAckSucceedsWhenAutoCommitOffsetIsTurnedOff", "test",
			moduleInputChannel, consumerProperties);

	String testPayload1 = "foo" + UUID.randomUUID().toString();
	Message<?> message1 = org.springframework.integration.support.MessageBuilder
			.withPayload(testPayload1.getBytes()).build();

	// Let the consumer actually bind to the producer before sending a msg
	binderBindUnbindLatency();
	moduleOutputChannel.send(message1);

	Message<?> receivedMessage = receive(moduleInputChannel);
	assertThat(receivedMessage).isNotNull();
	assertThat(receivedMessage.getHeaders().get(KafkaHeaders.ACKNOWLEDGMENT))
			.isNotNull();
	Acknowledgment acknowledgment = receivedMessage.getHeaders()
			.get(KafkaHeaders.ACKNOWLEDGMENT, Acknowledgment.class);
	try {
		acknowledgment.acknowledge();
	}
	catch (Exception e) {
		fail("Acknowledge must not throw an exception");
	}
	finally {
		producerBinding.unbind();
		consumerBinding.unbind();
	}
}
 
Example 10
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
@Test
public void testRoutingKeyExpression() throws Exception {
	RabbitTestBinder binder = getBinder();
	ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
	producerProperties.getExtension().setRoutingKeyExpression(
			spelExpressionParser.parseExpression("payload.field"));

	DirectChannel output = createBindableChannel("output",
			createProducerBindingProperties(producerProperties));
	output.setBeanName("rkeProducer");
	Binding<MessageChannel> producerBinding = binder.bindProducer("rke", output,
			producerProperties);

	RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());
	Queue queue = new AnonymousQueue();
	TopicExchange exchange = new TopicExchange("rke");
	org.springframework.amqp.core.Binding binding = BindingBuilder.bind(queue)
			.to(exchange).with("rkeTest");
	admin.declareQueue(queue);
	admin.declareBinding(binding);

	output.addInterceptor(new ChannelInterceptor() {

		@Override
		public Message<?> preSend(Message<?> message, MessageChannel channel) {
			assertThat(message.getHeaders()
					.get(RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER))
							.isEqualTo("rkeTest");
			return message;
		}

	});

	output.send(new GenericMessage<>(new Pojo("rkeTest")));

	Object out = spyOn(queue.getName()).receive(false);
	assertThat(out).isInstanceOf(byte[].class);
	assertThat(new String((byte[]) out, StandardCharsets.UTF_8))
			.isEqualTo("{\"field\":\"rkeTest\"}");

	producerBinding.unbind();
}
 
Example 11
Source File: AbstractBinderTests.java    From spring-cloud-stream with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void testSendAndReceiveMultipleTopics() throws Exception {
	Binder binder = getBinder();

	BindingProperties producerBindingProperties = createProducerBindingProperties(
			createProducerProperties());

	DirectChannel moduleOutputChannel1 = createBindableChannel("output1",
			producerBindingProperties);

	DirectChannel moduleOutputChannel2 = createBindableChannel("output2",
			producerBindingProperties);

	QueueChannel moduleInputChannel = new QueueChannel();

	Binding<MessageChannel> producerBinding1 = binder.bindProducer(
			String.format("foo%sxy", getDestinationNameDelimiter()),
			moduleOutputChannel1, producerBindingProperties.getProducer());
	Binding<MessageChannel> producerBinding2 = binder.bindProducer(
			String.format("foo%syz",

					getDestinationNameDelimiter()),
			moduleOutputChannel2, producerBindingProperties.getProducer());

	Binding<MessageChannel> consumerBinding1 = binder.bindConsumer(
			String.format("foo%sxy", getDestinationNameDelimiter()),
			"testSendAndReceiveMultipleTopics", moduleInputChannel,
			createConsumerProperties());
	Binding<MessageChannel> consumerBinding2 = binder.bindConsumer(
			String.format("foo%syz", getDestinationNameDelimiter()),
			"testSendAndReceiveMultipleTopics", moduleInputChannel,
			createConsumerProperties());

	String testPayload1 = "foo" + UUID.randomUUID().toString();
	Message<?> message1 = MessageBuilder.withPayload(testPayload1.getBytes())
			.setHeader(MessageHeaders.CONTENT_TYPE,
					MimeTypeUtils.APPLICATION_OCTET_STREAM)
			.build();
	String testPayload2 = "foo" + UUID.randomUUID().toString();
	Message<?> message2 = MessageBuilder.withPayload(testPayload2.getBytes())
			.setHeader(MessageHeaders.CONTENT_TYPE,
					MimeTypeUtils.APPLICATION_OCTET_STREAM)
			.build();

	// Let the consumer actually bind to the producer before sending a msg
	binderBindUnbindLatency();
	moduleOutputChannel1.send(message1);
	moduleOutputChannel2.send(message2);

	Message<?>[] messages = new Message[2];
	messages[0] = receive(moduleInputChannel);
	messages[1] = receive(moduleInputChannel);

	assertThat(messages[0]).isNotNull();
	assertThat(messages[1]).isNotNull();
	assertThat(messages).extracting("payload").containsExactlyInAnyOrder(
			testPayload1.getBytes(), testPayload2.getBytes());

	producerBinding1.unbind();
	producerBinding2.unbind();

	consumerBinding1.unbind();
	consumerBinding2.unbind();
}
 
Example 12
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testConfigurableDlqName() throws Exception {
	Binder binder = getBinder();

	ExtendedProducerProperties<KafkaProducerProperties> producerProperties = createProducerProperties();
	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();
	consumerProperties.setMaxAttempts(3);
	consumerProperties.setBackOffInitialInterval(100);
	consumerProperties.setBackOffMaxInterval(150);
	consumerProperties.getExtension().setEnableDlq(true);
	consumerProperties.getExtension().setAutoRebalanceEnabled(false);
	String dlqName = "dlqTest";
	consumerProperties.getExtension().setDlqName(dlqName);
	BindingProperties producerBindingProperties = createProducerBindingProperties(
			producerProperties);

	DirectChannel moduleOutputChannel = createBindableChannel("output",
			producerBindingProperties);

	DirectChannel moduleInputChannel = createBindableChannel("input",
			createConsumerBindingProperties(consumerProperties));

	FailingInvocationCountingMessageHandler handler = new FailingInvocationCountingMessageHandler();
	moduleInputChannel.subscribe(handler);

	long uniqueBindingId = System.currentTimeMillis();
	Binding<MessageChannel> producerBinding = binder.bindProducer(
			"retryTest." + uniqueBindingId + ".0", moduleOutputChannel,
			producerProperties);
	Binding<MessageChannel> consumerBinding = binder.bindConsumer(
			"retryTest." + uniqueBindingId + ".0", "testGroup", moduleInputChannel,
			consumerProperties);
	ExtendedConsumerProperties<KafkaConsumerProperties> dlqConsumerProperties = createConsumerProperties();
	dlqConsumerProperties.setMaxAttempts(1);
	QueueChannel dlqChannel = new QueueChannel();
	Binding<MessageChannel> dlqConsumerBinding = binder.bindConsumer(dlqName, null,
			dlqChannel, dlqConsumerProperties);

	String testMessagePayload = "test." + UUID.randomUUID().toString();
	Message<byte[]> testMessage = MessageBuilder
			.withPayload(testMessagePayload.getBytes()).build();
	moduleOutputChannel.send(testMessage);

	Message<?> dlqMessage = receive(dlqChannel, 3);
	assertThat(dlqMessage).isNotNull();
	assertThat(dlqMessage.getPayload()).isEqualTo(testMessagePayload.getBytes());

	// first attempt fails
	assertThat(handler.getReceivedMessages().entrySet()).hasSize(1);
	Message<?> handledMessage = handler.getReceivedMessages().entrySet().iterator()
			.next().getValue();
	assertThat(handledMessage).isNotNull();
	assertThat(
			new String((byte[]) handledMessage.getPayload(), StandardCharsets.UTF_8))
					.isEqualTo(testMessagePayload);
	assertThat(handler.getInvocationCount())
			.isEqualTo(consumerProperties.getMaxAttempts());
	binderBindUnbindLatency();
	dlqConsumerBinding.unbind();
	consumerBinding.unbind();

	// on the second attempt the message is not redelivered because the DLQ is set
	QueueChannel successfulInputChannel = new QueueChannel();
	consumerBinding = binder.bindConsumer("retryTest." + uniqueBindingId + ".0",
			"testGroup", successfulInputChannel, consumerProperties);
	String testMessage2Payload = "test." + UUID.randomUUID().toString();
	Message<byte[]> testMessage2 = MessageBuilder
			.withPayload(testMessage2Payload.getBytes()).build();
	moduleOutputChannel.send(testMessage2);

	Message<?> receivedMessage = receive(successfulInputChannel);
	assertThat(receivedMessage.getPayload())
			.isEqualTo(testMessage2Payload.getBytes());

	binderBindUnbindLatency();
	consumerBinding.unbind();
	producerBinding.unbind();
}
 
Example 13
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testAutoCreateTopicsDisabledOnBinderStillWorksAsLongAsBrokerCreatesTopic()
		throws Exception {
	KafkaBinderConfigurationProperties configurationProperties = createConfigurationProperties();
	configurationProperties.setAutoCreateTopics(false);
	Binder binder = getBinder(configurationProperties);
	BindingProperties producerBindingProperties = createProducerBindingProperties(
			createProducerProperties());
	DirectChannel output = createBindableChannel("output", producerBindingProperties);

	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();

	DirectChannel input = createBindableChannel("input",
			createConsumerBindingProperties(consumerProperties));

	String testTopicName = "createdByBroker-" + System.currentTimeMillis();

	Binding<MessageChannel> producerBinding = binder.bindProducer(testTopicName,
			output, producerBindingProperties.getProducer());

	String testPayload = "foo1-" + UUID.randomUUID().toString();
	output.send(new GenericMessage<>(testPayload));

	Binding<MessageChannel> consumerBinding = binder.bindConsumer(testTopicName,
			"test", input, consumerProperties);
	CountDownLatch latch = new CountDownLatch(1);
	AtomicReference<Message<byte[]>> inboundMessageRef = new AtomicReference<>();
	input.subscribe(message1 -> {
		try {
			inboundMessageRef.set((Message<byte[]>) message1);
		}
		finally {
			latch.countDown();
		}
	});
	Assert.isTrue(latch.await(5, TimeUnit.SECONDS), "Failed to receive message");

	assertThat(inboundMessageRef.get()).isNotNull();
	assertThat(
			new String(inboundMessageRef.get().getPayload(), StandardCharsets.UTF_8))
					.isEqualTo(testPayload);

	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example 14
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testDlqWithProducerPropertiesSetAtBinderLevel()
		throws Exception {

	KafkaBinderConfigurationProperties binderConfiguration = createConfigurationProperties();

	Map<String, String> consumerProps = new HashMap<>();
	consumerProps.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
	binderConfiguration.setConsumerProperties(consumerProps);

	Map<String, String> producerProps = new HashMap<>();
	producerProps.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
	binderConfiguration.setProducerProperties(producerProps);
	Binder binder = getBinder(binderConfiguration);

	ExtendedProducerProperties<KafkaProducerProperties> producerProperties = createProducerProperties();
	producerProperties.setUseNativeEncoding(true);
	BindingProperties outputBindingProperties = createProducerBindingProperties(
			producerProperties);
	DirectChannel moduleOutputChannel = createBindableChannel("output",
			outputBindingProperties);

	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();
	consumerProperties.setUseNativeDecoding(true);
	consumerProperties.getExtension().setEnableDlq(true);

	DirectChannel moduleInputChannel = createBindableChannel("input",
			createConsumerBindingProperties(consumerProperties));

	Binding<MessageChannel> producerBinding = binder.bindProducer("foo.bar",
			moduleOutputChannel, outputBindingProperties.getProducer());
	Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo.bar",
			"tdwcapsabl", moduleInputChannel, consumerProperties);

	// Let the consumer actually bind to the producer before sending a msg
	binderBindUnbindLatency();

	FailingInvocationCountingMessageHandler handler = new FailingInvocationCountingMessageHandler();
	moduleInputChannel.subscribe(handler);

	// Consumer for the DLQ destination
	QueueChannel dlqChannel = new QueueChannel();
	ExtendedConsumerProperties<KafkaConsumerProperties> dlqConsumerProperties = createConsumerProperties();
	dlqConsumerProperties.setMaxAttempts(1);

	Binding<MessageChannel> dlqConsumerBinding = binder.bindConsumer(
			"error.foo.bar." + "tdwcapsabl", null, dlqChannel,
			dlqConsumerProperties);
	binderBindUnbindLatency();

	Message<?> message = org.springframework.integration.support.MessageBuilder
			.withPayload("foo").build();

	moduleOutputChannel.send(message);

	Message<?> receivedMessage = dlqChannel.receive(5000);
	assertThat(receivedMessage).isNotNull();
	assertThat(receivedMessage.getPayload()).isEqualTo("foo");

	binderBindUnbindLatency();

	dlqConsumerBinding.unbind();

	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example 15
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@Test
@Override
@SuppressWarnings("unchecked")
public void testAnonymousGroup() throws Exception {
	Binder binder = getBinder();
	BindingProperties producerBindingProperties = createProducerBindingProperties(
			createProducerProperties());
	DirectChannel output = createBindableChannel("output", producerBindingProperties);
	Binding<MessageChannel> producerBinding = binder.bindProducer("defaultGroup.0",
			output, producerBindingProperties.getProducer());

	QueueChannel input1 = new QueueChannel();
	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();
	Binding<MessageChannel> binding1 = binder.bindConsumer("defaultGroup.0", null,
			input1, consumerProperties);

	QueueChannel input2 = new QueueChannel();
	Binding<MessageChannel> binding2 = binder.bindConsumer("defaultGroup.0", null,
			input2, consumerProperties);
	// Since we don't provide any topic info, let Kafka bind the consumer successfully
	Thread.sleep(1000);
	String testPayload1 = "foo-" + UUID.randomUUID().toString();
	output.send(new GenericMessage<>(testPayload1.getBytes()));

	Message<byte[]> receivedMessage1 = (Message<byte[]>) receive(input1);
	assertThat(receivedMessage1).isNotNull();
	assertThat(new String(receivedMessage1.getPayload(), StandardCharsets.UTF_8))
			.isEqualTo(testPayload1);

	Message<byte[]> receivedMessage2 = (Message<byte[]>) receive(input2);
	assertThat(receivedMessage2).isNotNull();
	assertThat(new String(receivedMessage2.getPayload(), StandardCharsets.UTF_8))
			.isEqualTo(testPayload1);

	binding2.unbind();

	String testPayload2 = "foo-" + UUID.randomUUID().toString();
	output.send(new GenericMessage<>(testPayload2.getBytes()));

	binding2 = binder.bindConsumer("defaultGroup.0", null, input2,
			consumerProperties);
	// Since we don't provide any topic info, let Kafka bind the consumer successfully
	Thread.sleep(1000);
	String testPayload3 = "foo-" + UUID.randomUUID().toString();
	output.send(new GenericMessage<>(testPayload3.getBytes()));

	receivedMessage1 = (Message<byte[]>) receive(input1);
	assertThat(receivedMessage1).isNotNull();
	assertThat(new String(receivedMessage1.getPayload(), StandardCharsets.UTF_8))
			.isEqualTo(testPayload2);
	receivedMessage1 = (Message<byte[]>) receive(input1);
	assertThat(receivedMessage1).isNotNull();
	assertThat(new String(receivedMessage1.getPayload(), StandardCharsets.UTF_8))
			.isNotNull();

	receivedMessage2 = (Message<byte[]>) receive(input2);
	assertThat(receivedMessage2).isNotNull();
	assertThat(new String(receivedMessage2.getPayload(), StandardCharsets.UTF_8))
			.isEqualTo(testPayload3);

	Map<String, TopicInformation> topicsInUse = ((KafkaTestBinder) binder)
			.getCoreBinder().getTopicsInUse();
	assertThat(topicsInUse.keySet()).contains("defaultGroup.0");
	TopicInformation topic = topicsInUse.get("defaultGroup.0");
	assertThat(topic.isConsumerTopic()).isTrue();
	assertThat(topic.getConsumerGroup()).startsWith("anonymous");

	producerBinding.unbind();
	binding1.unbind();
	binding2.unbind();
}
 
Example 16
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
@Ignore
public void testDlqWithNativeSerializationEnabledOnDlqProducer() throws Exception {
	Binder binder = getBinder();
	ExtendedProducerProperties<KafkaProducerProperties> producerProperties = createProducerProperties();

	// Native serialization for producer
	producerProperties.setUseNativeEncoding(true);
	Map<String, String> producerConfig = new HashMap<>();
	producerConfig.put("value.serializer",
			"org.apache.kafka.common.serialization.StringSerializer");
	producerProperties.getExtension().setConfiguration(producerConfig);

	BindingProperties outputBindingProperties = createProducerBindingProperties(
			producerProperties);

	DirectChannel moduleOutputChannel = createBindableChannel("output",
			outputBindingProperties);
	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();

	// Native Deserialization for consumer
	consumerProperties.setUseNativeDecoding(true);
	Map<String, String> consumerConfig = new HashMap<>();
	consumerConfig.put("value.deserializer",
			"org.apache.kafka.common.serialization.StringDeserializer");
	consumerProperties.getExtension().setConfiguration(consumerConfig);

	// Setting dlq producer properties on the consumer
	consumerProperties.getExtension()
			.setDlqProducerProperties(producerProperties.getExtension());
	consumerProperties.getExtension().setEnableDlq(true);

	DirectChannel moduleInputChannel = createBindableChannel("input",
			createConsumerBindingProperties(consumerProperties));

	Binding<MessageChannel> producerBinding = binder.bindProducer("foo.bar",
			moduleOutputChannel, outputBindingProperties.getProducer());
	Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo.bar",
			"testDlqWithNativeEncoding-1", moduleInputChannel, consumerProperties);

	// Let the consumer actually bind to the producer before sending a msg
	binderBindUnbindLatency();

	FailingInvocationCountingMessageHandler handler = new FailingInvocationCountingMessageHandler();
	moduleInputChannel.subscribe(handler);

	// Consumer for the DLQ destination
	QueueChannel dlqChannel = new QueueChannel();
	ExtendedConsumerProperties<KafkaConsumerProperties> dlqConsumerProperties = createConsumerProperties();
	dlqConsumerProperties.setMaxAttempts(1);

	Binding<MessageChannel> dlqConsumerBinding = binder.bindConsumer(
			"error.foo.bar." + "testDlqWithNativeEncoding-1", null, dlqChannel,
			dlqConsumerProperties);
	binderBindUnbindLatency();

	Message<?> message = org.springframework.integration.support.MessageBuilder
			.withPayload("foo").build();

	moduleOutputChannel.send(message);

	Message<?> receivedMessage = receive(dlqChannel, 5);
	assertThat(receivedMessage).isNotNull();
	assertThat(receivedMessage.getPayload()).isEqualTo("foo".getBytes());
	assertThat(handler.getInvocationCount())
			.isEqualTo(consumerProperties.getMaxAttempts());
	assertThat(receivedMessage.getHeaders()
			.get(KafkaMessageChannelBinder.X_ORIGINAL_TOPIC))
					.isEqualTo("foo.bar".getBytes(StandardCharsets.UTF_8));
	assertThat(new String((byte[]) receivedMessage.getHeaders()
			.get(KafkaMessageChannelBinder.X_EXCEPTION_MESSAGE))).startsWith(
					"Dispatcher failed to deliver Message; nested exception is java.lang.RuntimeException: fail");
	assertThat(receivedMessage.getHeaders()
			.get(KafkaMessageChannelBinder.X_EXCEPTION_STACKTRACE)).isNotNull();
	binderBindUnbindLatency();

	dlqConsumerBinding.unbind();

	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example 17
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
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("output",
			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();
}
 
Example 18
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@Test
@Override
@SuppressWarnings("unchecked")
public void testSendAndReceive() throws Exception {
	Binder binder = getBinder();
	BindingProperties outputBindingProperties = createProducerBindingProperties(
			createProducerProperties());
	DirectChannel moduleOutputChannel = createBindableChannel("output",
			outputBindingProperties);
	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();
	DirectChannel moduleInputChannel = createBindableChannel("input",
			createConsumerBindingProperties(consumerProperties));

	Binding<MessageChannel> producerBinding = binder.bindProducer("foo.bar",
			moduleOutputChannel, outputBindingProperties.getProducer());
	Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo.bar",
			"testSendAndReceive", moduleInputChannel, consumerProperties);
	Message<?> message = org.springframework.integration.support.MessageBuilder
			.withPayload("foo".getBytes(StandardCharsets.UTF_8))
			.setHeader(MessageHeaders.CONTENT_TYPE,
					MimeTypeUtils.APPLICATION_OCTET_STREAM)
			.build();

	// Let the consumer actually bind to the producer before sending a msg
	binderBindUnbindLatency();
	moduleOutputChannel.send(message);
	CountDownLatch latch = new CountDownLatch(1);
	AtomicReference<Message<byte[]>> inboundMessageRef = new AtomicReference<>();
	moduleInputChannel.subscribe(message1 -> {
		try {
			inboundMessageRef.set((Message<byte[]>) message1);
		}
		finally {
			latch.countDown();
		}
	});
	Assert.isTrue(latch.await(5, TimeUnit.SECONDS), "Failed to receive message");

	assertThat(inboundMessageRef.get()).isNotNull();
	assertThat(
			new String(inboundMessageRef.get().getPayload(), StandardCharsets.UTF_8))
					.isEqualTo("foo");
	assertThat(inboundMessageRef.get().getHeaders().get(MessageHeaders.CONTENT_TYPE))
			.isEqualTo(MimeTypeUtils.APPLICATION_OCTET_STREAM);

	Map<String, TopicInformation> topicsInUse = ((KafkaTestBinder) binder)
			.getCoreBinder().getTopicsInUse();
	assertThat(topicsInUse.keySet()).contains("foo.bar");
	TopicInformation topic = topicsInUse.get("foo.bar");
	assertThat(topic.isConsumerTopic()).isTrue();
	assertThat(topic.getConsumerGroup()).isEqualTo("testSendAndReceive");

	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example 19
Source File: KafkaTransactionTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testProducerRunsInTx() {
	KafkaProperties kafkaProperties = new TestKafkaProperties();
	kafkaProperties.setBootstrapServers(Collections
			.singletonList(embeddedKafka.getEmbeddedKafka().getBrokersAsString()));
	KafkaBinderConfigurationProperties configurationProperties = new KafkaBinderConfigurationProperties(
			kafkaProperties);
	configurationProperties.getTransaction().setTransactionIdPrefix("foo-");
	configurationProperties.getTransaction().getProducer().setUseNativeEncoding(true);
	KafkaTopicProvisioner provisioningProvider = new KafkaTopicProvisioner(
			configurationProperties, kafkaProperties);
	provisioningProvider.setMetadataRetryOperations(new RetryTemplate());
	final Producer mockProducer = mock(Producer.class);
	given(mockProducer.send(any(), any())).willReturn(new SettableListenableFuture<>());

	KafkaProducerProperties extension1 = configurationProperties
			.getTransaction().getProducer().getExtension();
	extension1.getConfiguration().put(ProducerConfig.RETRIES_CONFIG, "1");
	extension1.getConfiguration().put(ProducerConfig.ACKS_CONFIG, "all");

	willReturn(Collections.singletonList(new TopicPartition("foo", 0)))
			.given(mockProducer).partitionsFor(anyString());
	KafkaMessageChannelBinder binder = new KafkaMessageChannelBinder(
			configurationProperties, provisioningProvider) {

		@Override
		protected DefaultKafkaProducerFactory<byte[], byte[]> getProducerFactory(
				String transactionIdPrefix,
				ExtendedProducerProperties<KafkaProducerProperties> producerProperties, String beanName) {
			DefaultKafkaProducerFactory<byte[], byte[]> producerFactory = spy(
					super.getProducerFactory(transactionIdPrefix,
							producerProperties, beanName));
			willReturn(mockProducer).given(producerFactory).createProducer("foo-");
			return producerFactory;
		}

	};
	GenericApplicationContext applicationContext = new GenericApplicationContext();
	applicationContext.refresh();
	binder.setApplicationContext(applicationContext);
	DirectChannel channel = new DirectChannel();
	KafkaProducerProperties extension = new KafkaProducerProperties();
	ExtendedProducerProperties<KafkaProducerProperties> properties = new ExtendedProducerProperties<>(
			extension);
	binder.bindProducer("foo", channel, properties);
	channel.send(new GenericMessage<>("foo".getBytes()));
	InOrder inOrder = inOrder(mockProducer);
	inOrder.verify(mockProducer).beginTransaction();
	inOrder.verify(mockProducer).send(any(ProducerRecord.class), any(Callback.class));
	inOrder.verify(mockProducer).commitTransaction();
	inOrder.verify(mockProducer).close(any());
	inOrder.verifyNoMoreInteractions();
	assertThat(TestUtils.getPropertyValue(channel,
			"dispatcher.theOneHandler.useNativeEncoding", Boolean.class)).isTrue();
}
 
Example 20
Source File: RabbitBinderModuleTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
@Test
public void testParentConnectionFactoryInheritedByDefault() throws Exception {
	context = new SpringApplicationBuilder(SimpleProcessor.class)
			.web(WebApplicationType.NONE).run("--server.port=0",
					"--spring.cloud.stream.rabbit.binder.connection-name-prefix=foo",
					"--spring.cloud.stream.rabbit.bindings.input.consumer.single-active-consumer=true");
	BinderFactory binderFactory = context.getBean(BinderFactory.class);
	Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
	assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
	DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
	CachingConnectionFactory binderConnectionFactory = (CachingConnectionFactory) binderFieldAccessor
			.getPropertyValue("connectionFactory");
	assertThat(binderConnectionFactory).isInstanceOf(CachingConnectionFactory.class);
	ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);
	assertThat(binderConnectionFactory).isSameAs(connectionFactory);

	CompositeHealthContributor bindersHealthIndicator = context
			.getBean("bindersHealthContributor", CompositeHealthContributor.class);

	assertThat(bindersHealthIndicator).isNotNull();

	RabbitHealthIndicator indicator = (RabbitHealthIndicator) bindersHealthIndicator.getContributor("rabbit");
	assertThat(indicator).isNotNull();
	assertThat(indicator.health().getStatus())
			.isEqualTo(Status.UP);

	ConnectionFactory publisherConnectionFactory = binderConnectionFactory
			.getPublisherConnectionFactory();
	assertThat(TestUtils.getPropertyValue(publisherConnectionFactory,
			"connection.target")).isNull();
	DirectChannel checkPf = new DirectChannel();
	Binding<MessageChannel> binding = ((RabbitMessageChannelBinder) binder)
			.bindProducer("checkPF", checkPf,
					new ExtendedProducerProperties<>(new RabbitProducerProperties()));
	checkPf.send(new GenericMessage<>("foo".getBytes()));
	binding.unbind();
	assertThat(TestUtils.getPropertyValue(publisherConnectionFactory,
			"connection.target")).isNotNull();

	CachingConnectionFactory cf = this.context
			.getBean(CachingConnectionFactory.class);
	ConnectionNameStrategy cns = TestUtils.getPropertyValue(cf,
			"connectionNameStrategy", ConnectionNameStrategy.class);
	assertThat(cns.obtainNewConnectionName(cf)).isEqualTo("foo#2");
	new RabbitAdmin(rabbitTestSupport.getResource()).deleteExchange("checkPF");
	checkCustomizedArgs();
	binderConnectionFactory.resetConnection();
	binderConnectionFactory.createConnection();
	checkCustomizedArgs();
}