Binders with default settings inherit from module's configuration

Resolve #229

* Optimizes connection factory creation for binders that can use Boot's autoconfiguration
* Make binder contexts a child of main context when creating a Binder with default configuration settings
* Inherit environment from main context when the Binder context is not a child, and make that optional
* Default environment inheritance to true
* Tests
This commit is contained in:
Marius Bogoevici
2015-12-11 17:09:53 -05:00
parent 44d3fa4a90
commit a4f97b364e
9 changed files with 327 additions and 20 deletions

View File

@@ -66,6 +66,5 @@ public class RabbitServiceAutoConfiguration {
@Profile("!cloud")
@Import(RabbitAutoConfiguration.class)
protected static class NoCloudConfig {
}
}

View File

@@ -0,0 +1,125 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.stream.binder.rabbit.integration;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.ClassRule;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.binder.Binder;
import org.springframework.cloud.stream.binder.BinderFactory;
import org.springframework.cloud.stream.binder.rabbit.RabbitMessageChannelBinder;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.cloud.stream.test.junit.rabbit.RabbitTestSupport;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
/**
* @author Marius Bogoevici
*/
public class RabbitBinderModuleTests {
@ClassRule
public static RabbitTestSupport rabbitTestSupport = new RabbitTestSupport();
private ConfigurableApplicationContext context = null;
public static final ConnectionFactory MOCK_CONNECTION_FACTORY = Mockito.mock(ConnectionFactory.class, Mockito.RETURNS_MOCKS);
@After
public void tearDown() {
if (context != null) {
context.close();
context = null;
}
}
@Test
public void testParentConnectionFactoryInheritedByDefault() {
context = SpringApplication.run(SimpleProcessor.class);
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder binder = binderFactory.getBinder(null);
assertThat(binder, instanceOf(RabbitMessageChannelBinder.class));
DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
ConnectionFactory binderConnectionFactory =
(ConnectionFactory) binderFieldAccessor.getPropertyValue("connectionFactory");
assertThat(binderConnectionFactory, instanceOf(CachingConnectionFactory.class));
ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);
assertThat(binderConnectionFactory, is(connectionFactory));
}
@Test
public void testParentConnectionFactoryInheritedIfOverridden() {
context = new SpringApplication(SimpleProcessor.class, ConnectionFactoryConfiguration.class).run();
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder binder = binderFactory.getBinder(null);
assertThat(binder, instanceOf(RabbitMessageChannelBinder.class));
DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
ConnectionFactory binderConnectionFactory =
(ConnectionFactory) binderFieldAccessor.getPropertyValue("connectionFactory");
assertThat(binderConnectionFactory, is(MOCK_CONNECTION_FACTORY));
ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);
assertThat(binderConnectionFactory, is(connectionFactory));
}
@Test
public void testParentConnectionFactoryNotInheritedByCustomizedBinders() {
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");
context = SpringApplication.run(SimpleProcessor.class, params.toArray(new String[]{}));
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder binder = binderFactory.getBinder(null);
assertThat(binder, instanceOf(RabbitMessageChannelBinder.class));
DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
ConnectionFactory binderConnectionFactory =
(ConnectionFactory) binderFieldAccessor.getPropertyValue("connectionFactory");
ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);
assertThat(binderConnectionFactory, not(is(connectionFactory)));
}
@EnableBinding(Processor.class)
@SpringBootApplication
public static class SimpleProcessor {
}
public static class ConnectionFactoryConfiguration {
@Bean
public ConnectionFactory connectionFactory() {
return MOCK_CONNECTION_FACTORY;
}
}
}

View File

@@ -0,0 +1,125 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.stream.binder.redis.integration;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.ClassRule;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.binder.Binder;
import org.springframework.cloud.stream.binder.BinderFactory;
import org.springframework.cloud.stream.binder.redis.RedisMessageChannelBinder;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.cloud.stream.test.junit.redis.RedisTestSupport;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
/**
* @author Marius Bogoevici
*/
public class RedisBinderModuleTests {
@ClassRule
public static RedisTestSupport rabbitTestSupport = new RedisTestSupport();
private ConfigurableApplicationContext context = null;
public static final RedisConnectionFactory MOCK_CONNECTION_FACTORY = Mockito.mock(RedisConnectionFactory.class,
Mockito.RETURNS_MOCKS);
@After
public void tearDown() {
if (context != null) {
context.close();
context = null;
}
}
@Test
public void testParentConnectionFactoryInheritedByDefault() {
context = SpringApplication.run(SimpleProcessor.class);
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder binder = binderFactory.getBinder(null);
assertThat(binder, instanceOf(RedisMessageChannelBinder.class));
DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
RedisConnectionFactory binderConnectionFactory =
(RedisConnectionFactory) binderFieldAccessor.getPropertyValue("connectionFactory");
assertThat(binderConnectionFactory, instanceOf(RedisConnectionFactory.class));
RedisConnectionFactory connectionFactory = context.getBean(RedisConnectionFactory.class);
assertThat(binderConnectionFactory, is(connectionFactory));
}
@Test
public void testParentConnectionFactoryInheritedIfOverridden() {
context = new SpringApplication(SimpleProcessor.class, ConnectionFactoryConfiguration.class).run();
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder binder = binderFactory.getBinder(null);
assertThat(binder, instanceOf(RedisMessageChannelBinder.class));
DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
RedisConnectionFactory binderConnectionFactory =
(RedisConnectionFactory) binderFieldAccessor.getPropertyValue("connectionFactory");
assertThat(binderConnectionFactory, is(MOCK_CONNECTION_FACTORY));
RedisConnectionFactory connectionFactory = context.getBean(RedisConnectionFactory.class);
assertThat(binderConnectionFactory, is(connectionFactory));
}
@Test
public void testParentConnectionFactoryNotInheritedByCustomizedBinders() {
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=redis");
params.add("--spring.cloud.stream.binders.custom.environment.foo=bar");
context = SpringApplication.run(SimpleProcessor.class, params.toArray(new String[]{}));
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder binder = binderFactory.getBinder(null);
assertThat(binder, instanceOf(RedisMessageChannelBinder.class));
DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
RedisConnectionFactory binderConnectionFactory =
(RedisConnectionFactory) binderFieldAccessor.getPropertyValue("connectionFactory");
RedisConnectionFactory connectionFactory = context.getBean(RedisConnectionFactory.class);
assertThat(binderConnectionFactory, not(is(connectionFactory)));
}
@EnableBinding(Processor.class)
@SpringBootApplication
public static class SimpleProcessor {
}
public static class ConnectionFactoryConfiguration {
@Bean
public RedisConnectionFactory connectionFactory() {
return MOCK_CONNECTION_FACTORY;
}
}
}

View File

@@ -32,13 +32,17 @@ public class BinderConfiguration {
private final Properties properties;
private final boolean inheritEnvironment;
/**
* @param binderType the binder type used by this configuration
* @param properties the properties for setting up the binder
* @param inheritEnvironment whether the binder should inherit the environment of the module
*/
public BinderConfiguration(BinderType binderType, Properties properties) {
public BinderConfiguration(BinderType binderType, Properties properties, boolean inheritEnvironment) {
this.binderType = binderType;
this.properties = properties;
this.inheritEnvironment = inheritEnvironment;
}
public BinderType getBinderType() {
@@ -48,4 +52,8 @@ public class BinderConfiguration {
public Properties getProperties() {
return properties;
}
public boolean isInheritEnvironment() {
return inheritEnvironment;
}
}

View File

@@ -24,10 +24,10 @@ import java.util.Properties;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.Banner.Mode;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.util.StringUtils;
@@ -36,13 +36,13 @@ import org.springframework.util.StringUtils;
*
* @author Marius Bogoevici
*/
public class DefaultBinderFactory<T> implements BinderFactory<T>, DisposableBean, EnvironmentAware {
public class DefaultBinderFactory<T> implements BinderFactory<T>, DisposableBean, ApplicationContextAware {
private final Map<String, BinderConfiguration> binderConfigurations;
private final Map<String, BinderInstanceHolder<T>> binderInstanceCache = new HashMap<>();
private volatile Environment environment;
private volatile ConfigurableApplicationContext context;
private volatile String defaultBinder;
@@ -51,8 +51,8 @@ public class DefaultBinderFactory<T> implements BinderFactory<T>, DisposableBean
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
public void setApplicationContext(ApplicationContext applicationContext) {
this.context = (ConfigurableApplicationContext) applicationContext;
}
public void setDefaultBinder(String defaultBinder) {
@@ -104,7 +104,8 @@ public class DefaultBinderFactory<T> implements BinderFactory<T>, DisposableBean
args.add(String.format("--%s=%s",property.getKey(),property.getValue()));
}
// Initialize the domain with a unique name based on the bootstrapping context setting
String defaultDomain = this.environment != null ? this.environment.getProperty("spring.jmx.default-domain") : null;
ConfigurableEnvironment environment = context != null ? context.getEnvironment() : null;
String defaultDomain = environment != null ? environment.getProperty("spring.jmx.default-domain") : null;
if (defaultDomain == null) {
defaultDomain = "";
}
@@ -112,16 +113,22 @@ public class DefaultBinderFactory<T> implements BinderFactory<T>, DisposableBean
defaultDomain += ".";
}
args.add("--spring.jmx.default-domain=" + defaultDomain + "binder." + configurationName);
args.add("--spring.application.admin.enabled=false");
SpringApplicationBuilder springApplicationBuilder =
new SpringApplicationBuilder()
.sources(binderConfiguration.getBinderType().getConfigurationClasses())
.bannerMode(Mode.OFF)
.web(false);
if (this.environment instanceof ConfigurableEnvironment) {
StandardEnvironment environment = new StandardEnvironment();
environment.merge((ConfigurableEnvironment) this.environment);
springApplicationBuilder.environment(environment);
// If the environment is not customized and a main context is available, we will set the latter as parent.
// This ensures that the defaults and user-defined customizations (e.g. custom connection factory beans)
// are propagated to the binder context. If the environment is customized, then the binder context should
// not inherit any beans from the parent
if (binderProperties.isEmpty() && context != null) {
springApplicationBuilder.parent(context);
}
else if (environment != null && binderConfiguration.isInheritEnvironment()) {
StandardEnvironment binderEnvironment = new StandardEnvironment();
binderEnvironment.merge(environment);
springApplicationBuilder.environment(binderEnvironment);
}
ConfigurableApplicationContext binderProducingContext =
springApplicationBuilder.run(args.toArray(new String[args.size()]));

View File

@@ -62,21 +62,23 @@ public class BinderFactoryConfiguration {
if (binderTypeRegistry.get(binderEntry.getKey()) != null) {
binderConfigurations.put(binderEntry.getKey(),
new BinderConfiguration(binderTypeRegistry.get(binderEntry.getKey()),
binderProperties.getEnvironment()));
binderProperties.getEnvironment(), binderProperties.isInheritEnvironment()));
}
else {
Assert.hasText(binderProperties.getType(), "No 'type' property present for custom " +
"binder " + binderEntry.getKey());
BinderType binderType = binderTypeRegistry.get(binderProperties.getType());
Assert.notNull(binderType, "Binder type " + binderProperties.getType() + " is not defined");
binderConfigurations.put(binderEntry.getKey(),
new BinderConfiguration(binderTypeRegistry.get(binderProperties.getType()),
binderProperties.getEnvironment()));
new BinderConfiguration(binderType, binderProperties.getEnvironment(),
binderProperties.isInheritEnvironment()));
}
}
}
else {
for (Map.Entry<String, BinderType> entry : binderTypeRegistry.getAll().entrySet()) {
binderConfigurations.put(entry.getKey(),
new BinderConfiguration(entry.getValue(), new Properties()));
new BinderConfiguration(entry.getValue(), new Properties(), true));
}
}
DefaultBinderFactory binderFactory = new DefaultBinderFactory<>(binderConfigurations);

View File

@@ -28,6 +28,8 @@ public class BinderProperties {
private Properties environment = new Properties();
private boolean inheritEnvironment = true;
public String getType() {
return type;
}
@@ -44,4 +46,11 @@ public class BinderProperties {
this.environment = environment;
}
public boolean isInheritEnvironment() {
return inheritEnvironment;
}
public void setInheritEnvironment(boolean inheritEnvironment) {
this.inheritEnvironment = inheritEnvironment;
}
}

View File

@@ -24,6 +24,7 @@ import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
@@ -99,6 +100,33 @@ public class BinderFactoryConfigurationTests {
assertThat(((StubBinder1)binder1).getName(), is(equalTo("foo")));
}
@Test
public void loadBinderTypeRegistryWithOneCustomBinderAndSharedEnvironment() throws Exception {
ConfigurableApplicationContext context = createBinderTestContext(
new String[] {"binder1"}, "binder1.name=foo",
"spring.cloud.stream.binders.custom.properties.foo=bar",
"spring.cloud.stream.binders.custom.type=binder1");
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder binder1 = binderFactory.getBinder("custom");
assertThat(((StubBinder1)binder1).getName(), is(equalTo("foo")));
}
@Test
public void loadBinderTypeRegistryWithOneCustomBinderAndIsolatedEnvironment() throws Exception {
ConfigurableApplicationContext context = createBinderTestContext(
new String[] {"binder1"}, "binder1.name=foo",
"spring.cloud.stream.binders.custom.type=binder1",
"spring.cloud.stream.binders.custom.environment.foo=bar",
"spring.cloud.stream.binders.custom.inheritEnvironment=false");
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder binder1 = binderFactory.getBinder("custom");
assertThat(((StubBinder1)binder1).getName(),isEmptyOrNullString());
}
@Test
public void loadBinderTypeRegistryWithTwoBinders() throws Exception {

View File

@@ -51,7 +51,9 @@ public class ChannelBindingServiceTests {
properties.setBindings(bindings);
@SuppressWarnings("unchecked")
DefaultBinderFactory<MessageChannel> binderFactory =
new DefaultBinderFactory<>(Collections.singletonMap("mock", new BinderConfiguration(new BinderType("mock", new Class[]{MockBinderConfiguration.class}), new Properties())));
new DefaultBinderFactory<>(Collections.singletonMap("mock",
new BinderConfiguration(new BinderType("mock", new Class[]{MockBinderConfiguration.class}),
new Properties(), true)));
Binder<MessageChannel> binder = binderFactory.getBinder("mock");
ChannelBindingService service = new ChannelBindingService(properties, binderFactory);
MessageChannel inputChannel = new DirectChannel();
@@ -73,7 +75,9 @@ public class ChannelBindingServiceTests {
properties.setBindings(bindings);
@SuppressWarnings("unchecked")
DefaultBinderFactory<MessageChannel> binderFactory =
new DefaultBinderFactory<>(Collections.singletonMap("mock", new BinderConfiguration(new BinderType("mock", new Class[]{MockBinderConfiguration.class}), new Properties())));
new DefaultBinderFactory<>(Collections.singletonMap("mock",
new BinderConfiguration(new BinderType("mock", new Class[]{MockBinderConfiguration.class}),
new Properties(), true)));
Binder<MessageChannel> binder = binderFactory.getBinder("mock");
ChannelBindingService service = new ChannelBindingService(properties, binderFactory);
MessageChannel inputChannel = new DirectChannel();