故事背景
故事发生在几个星期前,自动化平台代码开放给整个测试团队以后,越来越多的同事开始探索平台代码。为了保障自动化测试相关的数据和沉淀能不被污染,把数据库进行了隔离。终于有了2个数据库实例,一个给dev环境用,一个给test环境用。可是随着平台的发展,越来越多的中间件被引用了。所以需要隔离的东西就越来越多了,比如MQ,Redis等。成本越来越高,如果像数据库实例一样全部分开搞一套,那在当下全域降本增效的大潮下,也是困难重重。
通过线下观察和走访发现,这些探索的同学并不是需要全平台的能力,其中有很多模块或者子系统,同学并不关心。因此就产生了一个想法,隔离掉这些类或者不使用这些和中间件相关的类应该就可以了 。而后因为我们的平台是基于springboot开发的,自然而然的想到了@Conditional注解。
调试&解决
以AWS SQS为例,先添加上了注解@ConditionalOnProperty根据配置信息中的coverage.aws.topic属性进行判断,如果存在这个配置就进行CoverageSQSConfig的Spring Bean的加载。
@Configuration
@ConditionalOnProperty(
name = "coverage.aws.topic"
)
public class CoverageSQSConfig {
@Value("${coverage.aws.region}")
private String awsRegion;
@Value("${coverage.aws.access.key}")
private String accessKey;
@Value("${coverage.aws.secret.key}")
private String secretKey;
@Bean(name = "coverageSQSListenerFactory")
public DefaultJmsListenerContainerFactory sqsListenerContainerFactory(){
return getDefaultJmsListenerContainerFactory(awsRegion, accessKey, secretKey);
}
private DefaultJmsListenerContainerFactory getDefaultJmsListenerContainerFactory(String awsRegion, String accessKey, String secretKey) {
DefaultJmsListenerContainerFactory sqsFactory = new DefaultJmsListenerContainerFactory();
sqsFactory.setConnectionFactory(new SQSConnectionFactory(
new ProviderConfiguration(),
AmazonSQSClientBuilder.standard()
.withRegion(Region.of(awsRegion).id())
.withCredentials(new