如何在服务发现库中禁用CompositeDiscoveryClient和SimpleDiscoveryClient

问题描述 投票:0回答:1

我们基于spring-cloud-commons SPI编写了一个内部服务发现(SD)客户端,这意味着它提供了接口ServiceRegistryDiscoveryClient以及其他一些Spring提供的抽象的实现。

使用我们库的应用程序只是将它添加到他们的pom文件中,并使用自己的实现自动装配DiscoveryClientInHouseDiscoveryClient

<dependency>
   <groupId>blah.blah<groupId>
   <artifactId>inhouse-service-discovery-client<artifactId>
<dependency>

但是,不是在代码中引用InHouseDiscoveryClient,而是使用接口DiscoveryClient的最佳实践,如下所示

# Good 
@Autowired
DiscoveryClient client;

# Bad (binds app to a particular SD implementation)
@Autowired
InHouseDiscoveryClient client;

因此,我们需要将spring-cloud-commons添加到项目中。

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-commons</artifactId>
    </dependency>

这是问题的开始。公共图书馆实际上自动增加了另外两个DiscoveryClient的实现 - SimpleDiscoveryClientCompositeDiscoveryClient

这为我们的客户带来了奇怪的用户体验。用户不仅可以使用InHouseDiscoveryClient,而且可以使用这些额外的bean。

是否有可能阻止spring-cloud-commonsDiscoveryClient实现自动装配?如果是这样,可以在我们的库中而不是在最终用户的应用程序中完成吗?

java spring spring-cloud service-discovery
1个回答
0
投票

我最终在我的库中扩展了AutoConfigurationImportFilter以从云公共中删除自动装配的bean。我也删除了它的健康指标,但我们有一个非常特别的理由这样做 - 最有可能宁愿保留它。

my.package

public class StratusDiscoveryExclusionFilter implements AutoConfigurationImportFilter {

private static final Set<String> SHOULD_SKIP = new HashSet<>(
        Arrays.asList(
                // DiscoveryClient Beans
                "org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClientAutoConfiguration",
                "org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration",
                // Health indicators
                "org.springframework.cloud.client.CommonsClientAutoConfiguration")
);

/**
 * For each class name, provide an assocated boolean array indicated whether or not to include
 */
@Override
public boolean[] match(String[] classNames, AutoConfigurationMetadata metadata) {
    boolean[] matches = new boolean[classNames.length];

    for (int i = 0; i < classNames.length; i++) {
        matches[i] = !SHOULD_SKIP.contains(classNames[i]);
    }
    return matches;
 }
}

我想在我的库的spring.factories文件中添加对此的引用

org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=my.package.MyExclusionFilter
© www.soinside.com 2019 - 2024. All rights reserved.