我想为此覆盖/actuator/health,我编写了一个自定义类(CustomHealth.java)并覆盖
getHealth()
但是我无法创建Bean,所以当我调用/actuator/health时,它必须调用我的自定义类实施。
自定义环境后处理器
Class CustomEnvironemtPostProcessor implements EnvironmentPostProcessor {
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
application.addInitializers(new CustomApplicationContextInitializer());
.....
}
}
自定义应用程序上下文初始化器
class CustomApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableListableBeanFactory beanFactory
= applicationContext.getBeanFactory();
beanFactory.registerSingleton("customHealth", CustomHealth.class);
}
}
定制健康
公共类 CustomHealth 实现 HealthIndicator {
public Health getHealth(boolean includeDetails) {
return this.health();
}
@Override
public Health health() {
double chance = ThreadLocalRandom.current().nextDouble();
Health.Builder status = Health.up();
if (chance > 0.9) {
status = Health.down();
}
return status.build();
}
}
通常您不需要为健康指标创建如此复杂的设置:
只需实现
HealthIndicator
接口并将其注册为Spring bean即可:
@Component
public class RandomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
double chance = ThreadLocalRandom.current().nextDouble();
Health.Builder status = Health.up();
if (chance > 0.9) {
status = Health.down();
}
return status.build();
}
}
代替
@Component
,您可以使用配置方法:
// no @Component annotation here
public class RandomHealthIndicator implements HealthIndicator {
...
}
@Configuration
public class MyHealthIndicatorExtensionsConfiguration {
@Bean
public RandomHealthIndicator randomHealthIndicator() {
return new RandomHealthIndicator();
}
}
有关完整示例和说明,请参阅此链接。