下面列出了org.springframework.validation.beanvalidation.CustomValidatorBean#org.springframework.cloud.stream.binder.BinderFactory 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testParentConnectionFactoryInheritedIfOverridden() {
context = new SpringApplicationBuilder(SimpleProcessor.class,
ConnectionFactoryConfiguration.class).web(WebApplicationType.NONE)
.run("--server.port=0");
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
.getPropertyValue("connectionFactory");
assertThat(binderConnectionFactory).isSameAs(MOCK_CONNECTION_FACTORY);
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();
// mock connection factory behaves as if down
assertThat(indicator.health().getStatus())
.isEqualTo(Status.DOWN);
}
@Test
public void testCloudProfile() {
this.context = new SpringApplicationBuilder(SimpleProcessor.class,
MockCloudConfiguration.class).web(WebApplicationType.NONE)
.profiles("cloud").run();
BinderFactory binderFactory = this.context.getBean(BinderFactory.class);
Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
.getPropertyValue("connectionFactory");
ConnectionFactory connectionFactory = this.context
.getBean(ConnectionFactory.class);
assertThat(binderConnectionFactory).isNotSameAs(connectionFactory);
assertThat(TestUtils.getPropertyValue(connectionFactory, "addresses"))
.isNotNull();
assertThat(TestUtils.getPropertyValue(binderConnectionFactory, "addresses"))
.isNull();
Cloud cloud = this.context.getBean(Cloud.class);
verify(cloud).getSingletonServiceConnector(ConnectionFactory.class, null);
}
@Test
public void testUnrecognizedBinderAllowedIfNotUsed() {
HashMap<String, String> properties = new HashMap<>();
properties.put("spring.cloud.stream.bindings.input.destination", "fooInput");
properties.put("spring.cloud.stream.bindings.output.destination", "fooOutput");
properties.put("spring.cloud.stream.defaultBinder", "mock1");
properties.put("spring.cloud.stream.binders.mock1.type", "mock");
properties.put("spring.cloud.stream.binders.kafka1.type", "kafka");
BindingServiceProperties bindingServiceProperties = createBindingServiceProperties(
properties);
BinderFactory binderFactory = new BindingServiceConfiguration()
.binderFactory(createMockBinderTypeRegistry(), bindingServiceProperties);
BindingService bindingService = new BindingService(bindingServiceProperties,
binderFactory);
bindingService.bindConsumer(new DirectChannel(), "input");
bindingService.bindProducer(new DirectChannel(), "output");
}
@Test
public void testUnrecognizedBinderDisallowedIfUsed() {
HashMap<String, String> properties = new HashMap<>();
properties.put("spring.cloud.stream.bindings.input.destination", "fooInput");
properties.put("spring.cloud.stream.bindings.input.binder", "mock1");
properties.put("spring.cloud.stream.bindings.output.destination", "fooOutput");
properties.put("spring.cloud.stream.bindings.output.type", "kafka1");
properties.put("spring.cloud.stream.binders.mock1.type", "mock");
properties.put("spring.cloud.stream.binders.kafka1.type", "kafka");
BindingServiceProperties bindingServiceProperties = createBindingServiceProperties(
properties);
BinderFactory binderFactory = new BindingServiceConfiguration()
.binderFactory(createMockBinderTypeRegistry(), bindingServiceProperties);
BindingService bindingService = new BindingService(bindingServiceProperties,
binderFactory);
bindingService.bindConsumer(new DirectChannel(), "input");
try {
bindingService.bindProducer(new DirectChannel(), "output");
fail("Expected 'Unknown binder configuration'");
}
catch (IllegalArgumentException e) {
assertThat(e).hasMessageContaining("Binder type kafka is not defined");
}
}
@Test
public void testExtendedPropertiesOverrideDefaults() {
BinderFactory binderFactory = this.context.getBeanFactory().getBean(BinderFactory.class);
PubSubMessageChannelBinder binder = (PubSubMessageChannelBinder) binderFactory.getBinder("pubsub",
MessageChannel.class);
assertThat(binder.getExtendedConsumerProperties("custom-in").isAutoCreateResources()).isFalse();
assertThat(binder.getExtendedConsumerProperties("input").isAutoCreateResources()).isTrue();
assertThat(binder.getExtendedConsumerProperties("custom-in").getAckMode())
.isEqualTo(AckMode.AUTO);
assertThat(binder.getExtendedConsumerProperties("input").getAckMode())
.isEqualTo(AckMode.AUTO_ACK);
}
@Bean
public PlatformTransactionManager transactionManager(BinderFactory binders) {
try {
ProducerFactory<byte[], byte[]> pf = ((KafkaMessageChannelBinder) binders.getBinder(null,
MessageChannel.class)).getTransactionalProducerFactory();
KafkaTransactionManager<byte[], byte[]> tm = new KafkaTransactionManager<>(pf);
tm.setTransactionSynchronization(AbstractPlatformTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
return tm;
}
catch (BeanCreationException e) { // needed to avoid other tests in this package failing when there is no binder
return null;
}
}
@Test
public void testExtendedProperties() {
context = new SpringApplicationBuilder(SimpleProcessor.class)
.web(WebApplicationType.NONE).run("--server.port=0",
"--spring.cloud.stream.rabbit.default.producer.routing-key-expression=fooRoutingKey",
"--spring.cloud.stream.rabbit.default.consumer.exchange-type=direct",
"--spring.cloud.stream.rabbit.bindings.output.producer.batch-size=512",
"--spring.cloud.stream.rabbit.default.consumer.max-concurrency=4",
"--spring.cloud.stream.rabbit.bindings.input.consumer.exchange-type=fanout");
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder<?, ?, ?> rabbitBinder = binderFactory.getBinder(null,
MessageChannel.class);
RabbitProducerProperties rabbitProducerProperties = (RabbitProducerProperties) ((ExtendedPropertiesBinder) rabbitBinder)
.getExtendedProducerProperties("output");
assertThat(
rabbitProducerProperties.getRoutingKeyExpression().getExpressionString())
.isEqualTo("fooRoutingKey");
assertThat(rabbitProducerProperties.getBatchSize()).isEqualTo(512);
RabbitConsumerProperties rabbitConsumerProperties = (RabbitConsumerProperties) ((ExtendedPropertiesBinder) rabbitBinder)
.getExtendedConsumerProperties("input");
assertThat(rabbitConsumerProperties.getExchangeType())
.isEqualTo(ExchangeTypes.FANOUT);
assertThat(rabbitConsumerProperties.getMaxConcurrency()).isEqualTo(4);
}
public BindingService(BindingServiceProperties bindingServiceProperties,
BinderFactory binderFactory, TaskScheduler taskScheduler) {
this.bindingServiceProperties = bindingServiceProperties;
this.binderFactory = binderFactory;
this.validator = new CustomValidatorBean();
this.validator.afterPropertiesSet();
this.taskScheduler = taskScheduler;
}
@Bean
// This conditional is intentionally not in an autoconfig (usually a bad idea) because
// it is used to detect a BindingService in the parent context (which we know
// already exists).
@ConditionalOnMissingBean(search = SearchStrategy.CURRENT)
public BindingService bindingService(
BindingServiceProperties bindingServiceProperties,
BinderFactory binderFactory, TaskScheduler taskScheduler) {
return new BindingService(bindingServiceProperties, binderFactory, taskScheduler);
}
@Bean
@SuppressWarnings("unchecked")
public BinderFactory binderFactory(final Binder<MessageChannel, ?, ?> binder) {
return new BinderFactory() {
@Override
public <T> Binder<T, ? extends ConsumerProperties, ? extends ProducerProperties> getBinder(
String configurationName, Class<? extends T> bindableType) {
return (Binder<T, ? extends ConsumerProperties, ? extends ProducerProperties>) binder;
}
};
}
@Test
public void testKafkaBinderExtendedProperties() throws Exception {
BinderFactory binderFactory = context.getBeanFactory()
.getBean(BinderFactory.class);
Binder<MessageChannel, ? extends ConsumerProperties, ? extends ProducerProperties> kafkaBinder = binderFactory
.getBinder("kafka", MessageChannel.class);
KafkaProducerProperties kafkaProducerProperties = (KafkaProducerProperties) ((ExtendedPropertiesBinder) kafkaBinder)
.getExtendedProducerProperties("standard-out");
// binding "standard-out" gets FooSerializer defined on the binding itself
// and BarSerializer through default property.
assertThat(kafkaProducerProperties.getConfiguration().get("key.serializer"))
.isEqualTo("FooSerializer.class");
assertThat(kafkaProducerProperties.getConfiguration().get("value.serializer"))
.isEqualTo("BarSerializer.class");
assertThat(kafkaProducerProperties.getConfiguration().get("foo"))
.isEqualTo("bindingSpecificPropertyShouldWinOverDefault");
// @checkstyle:off
KafkaConsumerProperties kafkaConsumerProperties = (KafkaConsumerProperties) ((ExtendedPropertiesBinder) kafkaBinder)
.getExtendedConsumerProperties("standard-in");
// @checkstyle:on
// binding "standard-in" gets FooSerializer defined on the binding itself
// and BarSerializer through default property.
assertThat(kafkaConsumerProperties.getConfiguration().get("key.serializer"))
.isEqualTo("FooSerializer.class");
assertThat(kafkaConsumerProperties.getConfiguration().get("value.serializer"))
.isEqualTo("BarSerializer.class");
// @checkstyle:off
KafkaProducerProperties customKafkaProducerProperties = (KafkaProducerProperties) ((ExtendedPropertiesBinder) kafkaBinder)
.getExtendedProducerProperties("custom-out");
// @checkstyle:on
// binding "standard-out" gets BarSerializer and BarSerializer for
// key.serializer/value.serializer through default properties.
assertThat(customKafkaProducerProperties.getConfiguration().get("key.serializer"))
.isEqualTo("BarSerializer.class");
assertThat(
customKafkaProducerProperties.getConfiguration().get("value.serializer"))
.isEqualTo("BarSerializer.class");
// through default properties.
assertThat(customKafkaProducerProperties.getConfiguration().get("foo"))
.isEqualTo("bar");
// @checkstyle:off
KafkaConsumerProperties customKafkaConsumerProperties = (KafkaConsumerProperties) ((ExtendedPropertiesBinder) kafkaBinder)
.getExtendedConsumerProperties("custom-in");
// @checkstyle:on
// binding "standard-in" gets BarSerializer and BarSerializer for
// key.serializer/value.serializer through default properties.
assertThat(customKafkaConsumerProperties.getConfiguration().get("key.serializer"))
.isEqualTo("BarSerializer.class");
assertThat(
customKafkaConsumerProperties.getConfiguration().get("value.serializer"))
.isEqualTo("BarSerializer.class");
assertThat(kafkaConsumerProperties.isAckEachRecord()).isEqualTo(true);
assertThat(customKafkaConsumerProperties.isAckEachRecord()).isEqualTo(false);
RebalanceListener rebalanceListener = context.getBean(RebalanceListener.class);
assertThat(rebalanceListener.latch.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(rebalanceListener.bindings.keySet()).contains("standard-in",
"custom-in");
assertThat(rebalanceListener.bindings.values()).containsExactly(Boolean.TRUE,
Boolean.TRUE);
}
@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();
}
@Test
@SuppressWarnings("unchecked")
public void testParentConnectionFactoryInheritedByDefaultAndRabbitSettingsPropagated() {
context = new SpringApplicationBuilder(SimpleProcessor.class)
.web(WebApplicationType.NONE).run("--server.port=0",
"--spring.cloud.stream.bindings.source.group=someGroup",
"--spring.cloud.stream.bindings.input.group=someGroup",
"--spring.cloud.stream.rabbit.bindings.input.consumer.transacted=true",
"--spring.cloud.stream.rabbit.bindings.output.producer.transacted=true");
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
BindingService bindingService = context.getBean(BindingService.class);
DirectFieldAccessor channelBindingServiceAccessor = new DirectFieldAccessor(
bindingService);
// @checkstyle:off
Map<String, List<Binding<MessageChannel>>> consumerBindings = (Map<String, List<Binding<MessageChannel>>>) channelBindingServiceAccessor
.getPropertyValue("consumerBindings");
// @checkstyle:on
Binding<MessageChannel> inputBinding = consumerBindings.get("input").get(0);
assertThat(TestUtils.getPropertyValue(inputBinding, "lifecycle.beanName"))
.isEqualTo("setByCustomizer:someGroup");
SimpleMessageListenerContainer container = TestUtils.getPropertyValue(
inputBinding, "lifecycle.messageListenerContainer",
SimpleMessageListenerContainer.class);
assertThat(TestUtils.getPropertyValue(container, "beanName"))
.isEqualTo("setByCustomizerForQueue:input.someGroup,andGroup:someGroup");
assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class))
.isTrue();
Map<String, Binding<MessageChannel>> producerBindings = (Map<String, Binding<MessageChannel>>) TestUtils
.getPropertyValue(bindingService, "producerBindings");
Binding<MessageChannel> outputBinding = producerBindings.get("output");
assertThat(TestUtils.getPropertyValue(outputBinding,
"lifecycle.amqpTemplate.transactional", Boolean.class)).isTrue();
assertThat(TestUtils.getPropertyValue(outputBinding, "lifecycle.beanName"))
.isEqualTo("setByCustomizer:output");
DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
ConnectionFactory binderConnectionFactory = (ConnectionFactory) 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);
CachingConnectionFactory cf = this.context
.getBean(CachingConnectionFactory.class);
ConnectionNameStrategy cns = TestUtils.getPropertyValue(cf,
"connectionNameStrategy", ConnectionNameStrategy.class);
assertThat(cns.obtainNewConnectionName(cf)).startsWith("rabbitConnectionFactory");
assertThat(TestUtils.getPropertyValue(consumerBindings.get("source").get(0),
"target.source.h.advised.targetSource.target.beanName"))
.isEqualTo("setByCustomizer:someGroup");
}
@Test
public void testParentConnectionFactoryNotInheritedByCustomizedBindersAndProducerRetryBootProperties() {
List<String> params = new ArrayList<>();
params.add("--spring.cloud.stream.input.binder=custom");
params.add("--spring.cloud.stream.output.binder=custom");
params.add("--spring.cloud.stream.binders.custom.type=rabbit");
params.add("--spring.cloud.stream.binders.custom.environment.foo=bar");
params.add("--server.port=0");
params.add("--spring.rabbitmq.template.retry.enabled=true");
params.add("--spring.rabbitmq.template.retry.maxAttempts=2");
params.add("--spring.rabbitmq.template.retry.initial-interval=1000");
params.add("--spring.rabbitmq.template.retry.multiplier=1.1");
params.add("--spring.rabbitmq.template.retry.max-interval=3000");
context = new SpringApplicationBuilder(SimpleProcessor.class)
.web(WebApplicationType.NONE)
.run(params.toArray(new String[params.size()]));
BinderFactory binderFactory = context.getBean(BinderFactory.class);
// @checkstyle:off
@SuppressWarnings("unchecked")
Binder<MessageChannel, ExtendedConsumerProperties<RabbitConsumerProperties>, ExtendedProducerProperties<RabbitProducerProperties>> binder = (Binder<MessageChannel, ExtendedConsumerProperties<RabbitConsumerProperties>, ExtendedProducerProperties<RabbitProducerProperties>>) binderFactory
.getBinder(null, MessageChannel.class);
// @checkstyle:on
assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
.getPropertyValue("connectionFactory");
ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);
assertThat(binderConnectionFactory).isNotSameAs(connectionFactory);
CompositeHealthContributor bindersHealthIndicator = context
.getBean("bindersHealthContributor", CompositeHealthContributor.class);
assertThat(bindersHealthIndicator);
RabbitHealthIndicator indicator = (RabbitHealthIndicator) bindersHealthIndicator.getContributor("custom");
assertThat(indicator).isNotNull();
assertThat(indicator.health().getStatus()).isEqualTo(Status.UP);
String name = UUID.randomUUID().toString();
Binding<MessageChannel> binding = binder.bindProducer(name, new DirectChannel(),
new ExtendedProducerProperties<>(new RabbitProducerProperties()));
RetryTemplate template = TestUtils.getPropertyValue(binding,
"lifecycle.amqpTemplate.retryTemplate", RetryTemplate.class);
assertThat(template).isNotNull();
SimpleRetryPolicy retryPolicy = TestUtils.getPropertyValue(template,
"retryPolicy", SimpleRetryPolicy.class);
ExponentialBackOffPolicy backOff = TestUtils.getPropertyValue(template,
"backOffPolicy", ExponentialBackOffPolicy.class);
assertThat(retryPolicy.getMaxAttempts()).isEqualTo(2);
assertThat(backOff.getInitialInterval()).isEqualTo(1000L);
assertThat(backOff.getMultiplier()).isEqualTo(1.1);
assertThat(backOff.getMaxInterval()).isEqualTo(3000L);
binding.unbind();
new RabbitAdmin(rabbitTestSupport.getResource()).deleteExchange(name);
context.close();
}
public BindingService(BindingServiceProperties bindingServiceProperties,
BinderFactory binderFactory) {
this(bindingServiceProperties, binderFactory, null);
}
@Bean
public MessageCollector messageCollector(BinderFactory binderFactory) {
return ((TestSupportBinder) binderFactory.getBinder("test", MessageChannel.class))
.messageCollector();
}