Skip to content

Introduced auto-configuration for MultiRabbit #25369

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ void documentConfigurationProperties() throws IOException {
"Hikari specific settings bound to an instance of Hikari's HikariDataSource")
.addSection("transaction").withKeyPrefixes("spring.jta", "spring.transaction").addSection("integration")
.withKeyPrefixes("spring.activemq", "spring.artemis", "spring.batch", "spring.integration",
"spring.jms", "spring.kafka", "spring.rabbitmq", "spring.hazelcast", "spring.webservices")
"spring.jms", "spring.kafka", "spring.rabbitmq", "spring.multirabbitmq", "spring.hazelcast",
"spring.webservices")
.addSection("actuator").withKeyPrefixes("management").addSection("devtools")
.withKeyPrefixes("spring.devtools").addSection("testing").withKeyPrefixes("spring.test");
DocumentOptions options = builder.build();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
* Copyright 2012-2021 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
*
* https://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.boot.autoconfigure.amqp;

import java.util.Map;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.impl.CredentialsProvider;
import com.rabbitmq.client.impl.CredentialsRefreshService;

import org.springframework.amqp.rabbit.config.RabbitListenerConfigUtils;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactoryContextWrapper;
import org.springframework.amqp.rabbit.connection.ConnectionNameStrategy;
import org.springframework.amqp.rabbit.connection.SimpleRoutingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration.RabbitConnectionFactoryCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ResourceLoader;

/**
* Class responsible for auto-configuring the necessary beans to enable multiple RabbitMQ
* servers.
*
* @author Wander Costa
* @since 2.4
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ RabbitTemplate.class, Channel.class })
@EnableConfigurationProperties({ RabbitProperties.class, MultiRabbitProperties.class })
@Import(RabbitAnnotationDrivenConfiguration.class)
public class MultiRabbitAutoConfiguration {

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "spring.multirabbitmq", name = "enabled", havingValue = "true")
protected static class MultiRabbitConnectionFactoryCreator extends RabbitConnectionFactoryCreator
implements BeanFactoryAware, ApplicationContextAware {

private ConfigurableListableBeanFactory beanFactory;

private ApplicationContext applicationContext;

@Bean
@ConditionalOnMissingBean
public ConnectionFactoryContextWrapper contextWrapper(
@Qualifier(RabbitListenerConfigUtils.RABBIT_CONNECTION_FACTORY_BEAN_NAME) final ConnectionFactory connectionFactory) {
return new ConnectionFactoryContextWrapper(connectionFactory);
}

@Primary
@Bean(RabbitListenerConfigUtils.RABBIT_CONNECTION_FACTORY_BEAN_NAME)
public ConnectionFactory routingConnectionFactory(final RabbitProperties rabbitProperties,
final MultiRabbitProperties multiRabbitProperties, final ResourceLoader resourceLoader,
final ObjectProvider<CredentialsProvider> credentialsProvider,
final ObjectProvider<CredentialsRefreshService> credentialsRefreshService,
final ObjectProvider<ConnectionNameStrategy> connectionNameStrategy) throws Exception {
final MultiRabbitConnectionFactoryWrapper wrapper = new MultiRabbitConnectionFactoryWrapper();
final ConnectionFactory defaultConnectionFactory = super.rabbitConnectionFactory(rabbitProperties,
resourceLoader, credentialsProvider, credentialsRefreshService, connectionNameStrategy);
wrapper.setDefaultConnectionFactory(defaultConnectionFactory);
this.registerNewContainerFactoryBean(RabbitListenerConfigUtils.MULTI_RABBIT_CONTAINER_FACTORY_BEAN_NAME,
defaultConnectionFactory);
this.registerNewRabbitAdminBean(RabbitListenerConfigUtils.RABBIT_ADMIN_BEAN_NAME, defaultConnectionFactory);

for (final Map.Entry<String, RabbitProperties> entry : multiRabbitProperties.getConnections().entrySet()) {
final String key = entry.getKey();
final RabbitProperties properties = entry.getValue();
final ConnectionFactory connectionFactory = super.rabbitConnectionFactory(properties, resourceLoader,
credentialsProvider, credentialsRefreshService, connectionNameStrategy);
this.registerNewContainerFactoryBean(key, connectionFactory);
this.registerNewRabbitAdminBean(key.concat(RabbitListenerConfigUtils.MULTI_RABBIT_ADMIN_SUFFIX),
connectionFactory);
wrapper.addConnectionFactory(key, connectionFactory);
}

final SimpleRoutingConnectionFactory connectionFactory = new SimpleRoutingConnectionFactory();
connectionFactory.setTargetConnectionFactories(wrapper.getConnectionFactories());
connectionFactory.setDefaultTargetConnectionFactory(wrapper.getDefaultConnectionFactory());
return connectionFactory;
}

private void registerNewContainerFactoryBean(final String name, final ConnectionFactory connectionFactory) {
final SimpleRabbitListenerContainerFactory containerFactory = new SimpleRabbitListenerContainerFactory();
containerFactory.setApplicationContext(this.applicationContext);
containerFactory.setConnectionFactory(connectionFactory);
this.beanFactory.registerSingleton(name, containerFactory);
}

private void registerNewRabbitAdminBean(final String name, final ConnectionFactory connectionFactory) {
final RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
rabbitAdmin.setApplicationContext(this.applicationContext);
rabbitAdmin.setBeanName(name);
rabbitAdmin.afterPropertiesSet();
this.beanFactory.registerSingleton(name, rabbitAdmin);
}

@Override
public void setBeanFactory(final BeanFactory beanFactory) {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}

@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright 2012-2021 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
*
* https://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.boot.autoconfigure.amqp;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.util.Assert;

/**
* A wrapper for RabbitMQ structures to offer an easy way to integrate with MultiRabbit.
* It's backed by a {@link HashMap} that holds all non-default structures, but does not
* allow null keys since there is a default field holding .
*
* @author Wander Costa
* @since 2.4
*/
public class MultiRabbitConnectionFactoryWrapper {

private final Map<Object, ConnectionFactory> connectionFactories = new HashMap<>();

private final Map<Object, ConnectionFactory> unmodifiableMapReference = Collections
.unmodifiableMap(this.connectionFactories);

private ConnectionFactory defaultConnectionFactory;

public void setDefaultConnectionFactory(final ConnectionFactory connectionFactory) {
this.defaultConnectionFactory = connectionFactory;
}

ConnectionFactory getDefaultConnectionFactory() {
return this.defaultConnectionFactory;
}

public void addConnectionFactory(final String key, final ConnectionFactory connectionFactory) {
Assert.hasText(key, "Key may not be null or empty");
this.connectionFactories.put(key, connectionFactory);
}

Map<Object, ConnectionFactory> getConnectionFactories() {
return this.unmodifiableMapReference;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright 2012-2021 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
*
* https://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.boot.autoconfigure.amqp;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.springframework.amqp.rabbit.config.RabbitListenerConfigUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.lang.Nullable;

/**
* Configuration properties for multiple Rabbit.
*
* @author Wander Costa
* @see RabbitProperties
* @since 2.4
*/
@ConfigurationProperties(prefix = "spring.multirabbitmq")
public class MultiRabbitProperties {

/**
* A flag to enable/disable MultiRabbit processing.
*/
@Value("${" + RabbitListenerConfigUtils.MULTI_RABBIT_ENABLED_PROPERTY + "}")
private boolean enabled;

/**
* A map representing the RabbitProperties of all available brokers.
*/
private Map<String, RabbitProperties> connections = new HashMap<>();

public boolean isEnabled() {
return this.enabled;
}

public void setEnabled(boolean enabled) {
this.enabled = enabled;
}

public Map<String, RabbitProperties> getConnections() {
return this.connections;
}

public void setConnections(@Nullable final Map<String, RabbitProperties> connections) {
this.connections = Optional.ofNullable(connections).orElse(new HashMap<>());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import com.rabbitmq.client.impl.CredentialsRefreshService;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.rabbit.config.RabbitListenerConfigUtils;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionNameStrategy;
Expand Down Expand Up @@ -96,7 +97,7 @@ public class RabbitAutoConfiguration {
@ConditionalOnMissingBean(ConnectionFactory.class)
protected static class RabbitConnectionFactoryCreator {

@Bean
@Bean(RabbitListenerConfigUtils.RABBIT_CONNECTION_FACTORY_BEAN_NAME)
public CachingConnectionFactory rabbitConnectionFactory(RabbitProperties properties,
ResourceLoader resourceLoader, ObjectProvider<CredentialsProvider> credentialsProvider,
ObjectProvider<CredentialsRefreshService> credentialsRefreshService,
Expand Down Expand Up @@ -187,7 +188,7 @@ public RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, Connec
return template;
}

@Bean
@Bean(RabbitListenerConfigUtils.RABBIT_ADMIN_BEAN_NAME)
@ConditionalOnSingleCandidate(ConnectionFactory.class)
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)
@ConditionalOnMissingBean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1649,6 +1649,16 @@
"level": "error"
}
},
{
"name": "spring.multirabbitmq.enabled",
"type": "java.lang.Boolean",
"description": "The flag to enable/disable MultiRabbit processing."
},
{
"name": "spring.multirabbitmq.connections",
"type": "java.util.Map<java.lang.String,org.springframework.boot.autoconfigure.amqp.RabbitProperties>",
"description": "The Map containing all the connections."
},
{
"name": "spring.reactor.stacktrace-mode.enabled",
"description": "Whether Reactor should collect stacktrace information at runtime.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.MultiRabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2012-2021 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
*
* https://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.boot.autoconfigure.amqp;

import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;

/**
* Tests to ensure compatibility of {@link MultiRabbitAutoConfiguration} with
* {@link RabbitAutoConfiguration} if MultiRabbit is not enabled.
*
* @author Wander Costa
*/
class MultiRabbitAutoConfigurationCompatibilityTest extends RabbitAutoConfigurationTests {

MultiRabbitAutoConfigurationCompatibilityTest() {
super.contextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(MultiRabbitAutoConfiguration.class, RabbitAutoConfiguration.class));
}

}
Loading