可能有更好的方法来获取健康数据,但这对我有用。
@RestController
public class HealthController {
@Autowired
HealthContributor[] healthContributors;
@GetMapping("/health")
public Map<String, String> health() {
Map<String, String> components = new HashMap<String, String>();
for(HealthContributor healthContributor : healthContributors) {
String componentName = healthContributor.getClass().getSimpleName().replace("HealthIndicator", "").replace("HealthCheckIndicator", "");
String status = ((HealthIndicator)(healthContributor)).health().getStatus().toString();
//To get details
//Map<String,Object> details = ((HealthIndicator)(healthContributor)).health().getDetails();
components.put(componentName, status);
}
return components;
}
}
示例输出:
{
"Mail":"UP",
"Ping":"UP",
"Camel":"UP",
"DiskSpace":"UP"
}
要模拟 HealthContributor[],您可以尝试使用 Mockito,如下所示:
@Profile("test")
@Configuration
public class HealthContributorsMockConfig {
@Primary
@Bean(name = "healthContributors")
public HealthContributor[] healthContributors() {
HealthContributor[] healthContributors = new HealthContributor[2];
HealthContributor healthContributorA = Mockito.mock(HealthIndicator.class, new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
// TODO Auto-generated method stub
Health health = Health.up().build();
return health;
}
});
HealthContributor healthContributorB = Mockito.mock(HealthIndicator.class, new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
// TODO Auto-generated method stub
Health health = Health.down().build();
return health;
}
});
healthContributors[0] = healthContributorA;
healthContributors[1] = healthContributorB;
return healthContributors;
}
}