3

我打算使用spring-boot-actuatorHealtCheckContributors为 Spring Boot 应用程序编写一些内容。因此,我实现了其中两个。当然,它们旨在检查不同应用程序的运行状况,但具有几乎相同的结构,除了配置属性,...

SonarQube 对此抱怨,我想知道是否可以有一个单一的健康检查类,但实例化的次数与application.properties. 一个例子:

application.properties

# actuator
app1.management.baseUrl=http://localhost:10000
app1.management.name=app1HealthCheckContributor
app2.management.basUrl=http://localhost:10001
app2.management.name=app2HealthCheckContributor

HealthCheckContributor对于应用程序1:

@Slf4j
@Component("xxx")
public class App1HealthCheckContributor extends AbstractHealthIndicator {

    private final App1Properties app1Properties;

    public App1HealthCheckContributor(final App1Properties app1Properties) {
        this.app1Properties = app1Properties;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) {...}
}

...并且此代码HealthCheckContributor仅在其appXProperties中有所不同。

不可能有某种基类,如:

@Slf4j
@Component()
public class MyHealthCheckContributor extends AbstractHealthIndicator {

    private final MyProperties myProperties;

    public MyHealthCheckContributor(final MyProperties myProperties) {
        this.myProperties = myProperties;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) {...}
}

并让 Spring Boot 负责实例化两个HealthCheckContributors(在我们的例子中App1HealthCheckContributorApp2HealthCheckContributor)?这将消除代码重复。

属性类文件的示例:

@Slf4j
@Data
@ConfigurationProperties(prefix = "app1.management")
public class App1Properties {
    private String baseUrl;
    private String ...;
}

我怎样才能做到这一点以及application.properties文件看起来如何才能实现我打算做的事情?

最后一个问题:如何测试一个类的 bean 的多个实例创建,其中填充了 application.properties 中的值?

4

1 回答 1

1

假设doHealthCheck要检查的所有应用程序中的代码完全相同,您可以执行以下操作。

您将从创建一个健康检查类开始:

@Slf4j
public class AppHealthCheckContributor extends AbstractHealthIndicator {

    private final AppProperties appProperties;

    public App1HealthCheckContributor(final AppProperties appProperties) {
        this.appProperties = appProperties;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) {...}
}

属性模型如下:

@Slf4j
@Data
public class AppProperties {
    private String baseUrl;
    private String name;
}

这意味着配置将类似于以下内容(in application.yml):

health-check:
  apps:
    - baseUrl: http://localhost:10000
      name: app1
    - baseUrl: http://localhost:10001
      name: app2

最后,您需要为每个应用程序创建一个 bean 并将它们注册到应用程序上下文中:

@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "health-check")
public class AllAppPropertiesConfiguration {
    private List<AppProperties> apps;

    @Autowired
    private GenericApplicationContext applicationContext;

    @PostConstruct
    fun init() {
        for (AppProperties app : apps) {
            applicationContext.registerBean(app.getName(), AppHealthCheckContributor.class, app);
        }
    }
}
于 2021-10-14T17:29:50.220 回答