下面列出了怎么用org.springframework.boot.actuate.health.HealthIndicator的API类实例代码及写法,或者点击链接到github查看源代码。
private static int getStatusCode(HealthIndicator healthIndicator) {
if (!running) {
return 0;
}
switch (healthIndicator.health().getStatus().getCode()) {
case "UP":
return 3;
case "OUT_OF_SERVICE":
return 2;
case "DOWN":
return 1;
case "UNKNOWN":
default:
return 0;
}
}
@Bean
@Autowired(required = false)
@ConditionalOnMissingBean
public HealthIndicator jikexiuHealthIndicator(RedisQueueImpl redisQueue,
RedisQueueProperties properties) {
CompositeHealthIndicator compositeHealthIndicator = new
CompositeHealthIndicator(healthAggregator);
Map<String, LeaderManager> leaderManagerMap = AppEnvContext.getCtx().getBeansOfType(LeaderManager.class);
LeaderManager manager = null;
if (leaderManagerMap != null && !leaderManagerMap.isEmpty()) {
manager = AppEnvContext.getCtx().getBean(SimpleLeaderManager.class);
}
compositeHealthIndicator.addHealthIndicator("dq", new QueueHealthIndicator(
redisQueue, manager, properties));
return compositeHealthIndicator;
}
@Bean
HealthIndicator redisHealth(JedisPool jedisPool) {
return () -> {
Jedis jedis = null;
Health.Builder health = null;
try {
jedis = jedisPool.getResource();
if ("PONG".equals(jedis.ping())) {
health = Health.up();
} else {
health = Health.down();
}
} catch (Exception ex) {
health = Health.down(ex);
} finally {
if (jedis != null) {
jedis.close();
}
}
return health.build();
};
}
/**
* Creates a HealthIndicator based on the channels' {@link ConnectivityState}s from the underlying
* {@link GrpcChannelFactory}.
*
* @param factory The factory to derive the connectivity states from.
* @return A health indicator bean, that uses the following assumption
* <code>DOWN == states.contains(TRANSIENT_FAILURE)</code>.
*/
@Bean
@Lazy
public HealthIndicator grpcChannelHealthIndicator(final GrpcChannelFactory factory) {
return () -> {
final ImmutableMap<String, ConnectivityState> states = ImmutableMap.copyOf(factory.getConnectivityState());
final Health.Builder health;
if (states.containsValue(ConnectivityState.TRANSIENT_FAILURE)) {
health = Health.down();
} else {
health = Health.up();
}
return health.withDetails(states)
.build();
};
}
/**
* Creates a HealthIndicator based on the channels' {@link ConnectivityState}s from the underlying
* {@link GrpcChannelFactory}.
*
* @param factory The factory to derive the connectivity states from.
* @return A health indicator bean, that uses the following assumption
* <code>DOWN == states.contains(TRANSIENT_FAILURE)</code>.
*/
@Bean
@Lazy
public HealthIndicator grpcChannelHealthIndicator(final GrpcChannelFactory factory) {
return () -> {
final ImmutableMap<String, ConnectivityState> states = ImmutableMap.copyOf(factory.getConnectivityState());
final Health.Builder health;
if (states.containsValue(ConnectivityState.TRANSIENT_FAILURE)) {
health = Health.down();
} else {
health = Health.up();
}
return health.withDetails(states)
.build();
};
}
private NamedContributor<HealthContributor> asNamedContributor(
DiscoveryHealthIndicator indicator) {
return new NamedContributor<HealthContributor>() {
@Override
public String getName() {
return indicator.getName();
}
@Override
public HealthIndicator getContributor() {
return asHealthIndicator(indicator);
}
};
}
void populateHealthIndicators(Map<String, HealthIndicator> healthIndicators) {
for (Map.Entry<String, HealthIndicator> entry : healthIndicators.entrySet()) {
// ignore EurekaHealthIndicator and flatten the rest of the composite
// otherwise there is a never ending cycle of down. See gh-643
if (entry.getValue() instanceof DiscoveryCompositeHealthContributor) {
DiscoveryCompositeHealthContributor indicator = (DiscoveryCompositeHealthContributor) entry
.getValue();
indicator.forEach(contributor -> {
if (!(contributor
.getContributor() instanceof EurekaHealthIndicator)) {
this.healthIndicators.put(contributor.getName(),
(HealthIndicator) contributor.getContributor());
}
});
}
else {
this.healthIndicators.put(entry.getKey(), entry.getValue());
}
}
}
@Bean
@Autowired(required = false)
@ConditionalOnMissingBean
public HealthIndicator jikexiuHealthIndicator(RedisQueue redisQueue, RedisQueueProperties properties) {
CompositeHealthIndicator compositeHealthIndicator = new CompositeHealthIndicator(healthAggregator);
Map<String, LeaderManager> leaderManagerMap = AppEnvContext.getCtx().getBeansOfType(LeaderManager.class);
LeaderManager manager = null;
if (leaderManagerMap != null && !leaderManagerMap.isEmpty()) {
manager = AppEnvContext.getCtx().getBean(SimpleLeaderManager.class);
}
compositeHealthIndicator.addHealthIndicator(Constants.HEALTH_INDICATOR_NAME, new QueueHealthIndicator(redisQueue, manager, properties));
return compositeHealthIndicator;
}
@Bean
CompositeHealthContributor grpcServices(GrpcServiceDiscoverer grpcServiceDiscoverer,
HealthStatusManager healthStatusManager) {
Map<String, HealthIndicator> healthIndicators = new LinkedHashMap<>();
for (GrpcServiceDefinition grpcService : grpcServiceDiscoverer.findGrpcServices()) {
String serviceName = grpcService.getDefinition().getServiceDescriptor().getName();
healthIndicators.put(serviceName, new GrpcHealthIndicator(healthStatusManager, serviceName));
}
return CompositeHealthContributor.fromMap(healthIndicators);
}
public HealthMetricsConfiguration(HealthAggregator healthAggregator, List<HealthIndicator> healthIndicators,
MeterRegistry registry, PlatformTag platformTag) {
healthIndicator = new CompositeHealthIndicator(healthAggregator);
healthIndicators.forEach(h -> {
registry.gauge("health." + h.getClass().getSimpleName().replace("HealthIndicator", "").toLowerCase(),
platformTag.getTags(), h, HealthMetricsConfiguration::getStatusCode);
healthIndicator.addHealthIndicator(h.toString(), h);
});
registry.gauge("health", platformTag.getTags(), healthIndicator, HealthMetricsConfiguration::getStatusCode);
}
@Bean
public HealthIndicator dbCountHealthIndicator(Collection<CrudRepository> repositories) {
CompositeHealthIndicator compositeHealthIndicator = new CompositeHealthIndicator(healthAggregator);
for (CrudRepository repository : repositories) {
String name = DbCountRunner.getRepositoryName(repository.getClass());
compositeHealthIndicator.addHealthIndicator(name, new DbCountHealthIndicator(repository));
}
return compositeHealthIndicator;
}
@Bean
public HealthIndicator dbCountHealthIndicator(Collection<CrudRepository> repositories) {
CompositeHealthIndicator compositeHealthIndicator = new CompositeHealthIndicator(healthAggregator);
for (CrudRepository repository : repositories) {
String name = DbCountRunner.getRepositoryName(repository.getClass());
compositeHealthIndicator.addHealthIndicator(name, new DbCountHealthIndicator(repository));
}
return compositeHealthIndicator;
}
@Bean
public HealthIndicator dbCountHealthIndicator(Collection<CrudRepository> repositories) {
CompositeHealthIndicator compositeHealthIndicator = new CompositeHealthIndicator(healthAggregator);
for (CrudRepository repository : repositories) {
String name = DbCountRunner.getRepositoryName(repository.getClass());
compositeHealthIndicator.addHealthIndicator(name, new DbCountHealthIndicator(repository));
}
return compositeHealthIndicator;
}
@Bean(BEAN_NAME)
public HealthIndicator diskSpaceHealthIndicator(HealthAggregator healthAggregator, DiskSpaceHealthProperties conf) {
if (logger.isInfoEnabled())
logger.info("Initial diskSpaceHealthIndicator. {}", conf);
AdvancedDiskSpaceHealthIndicator healthIndicator = new AdvancedDiskSpaceHealthIndicator(conf);
Map<String, Health> healths = new LinkedHashMap<String, Health>();
healths.put(AdvancedDiskSpaceHealthIndicator.class.getSimpleName(), healthIndicator.health());
return healthIndicator;
}
@Bean
public HealthIndicator timeoutsHealthIndicator(HealthAggregator healthAggregator, TimerMetricsProperties conf) {
if (conf.getSamples() == 0)
throw new IllegalArgumentException("Latest measure count is 0.");
if (logger.isInfoEnabled())
logger.info("Initial timeoutsHealthIndicator. {}", conf);
TimeoutsHealthIndicator healthIndicator = new TimeoutsHealthIndicator(conf);
Map<String, Health> healths = new LinkedHashMap<String, Health>();
healths.put(TimeoutsHealthIndicator.class.getSimpleName(), healthIndicator.health());
return healthIndicator;
}
@Bean(BEAN_NAME)
public HealthIndicator memoryHealthIndicator(HealthAggregator healthAggregator, MemoryHealthProperties conf) {
if (logger.isInfoEnabled())
logger.info("Initial memoryHealthIndicator. {}", conf);
AdvancedMemoryHealthIndicator healthIndicator = new AdvancedMemoryHealthIndicator(conf);
Map<String, Health> healths = new LinkedHashMap<String, Health>();
healths.put(AdvancedMemoryHealthIndicator.class.getSimpleName(), healthIndicator.health());
return healthIndicator;
}
@Bean(BEAN_NAME)
public HealthIndicator coreHealthIndicator(HealthAggregator healthAggregator, CpuHealthProperties conf) {
if (logger.isInfoEnabled())
logger.info("Initial CoreHealthIndicator. {}", conf);
AdvancedCpuHealthIndicator healthIndicator = new AdvancedCpuHealthIndicator(conf);
Map<String, Health> healths = new LinkedHashMap<String, Health>();
healths.put(AdvancedCpuHealthIndicator.class.getSimpleName(), healthIndicator.health());
return healthIndicator;
}
public SidecarHealthChecker(SidecarDiscoveryClient sidecarDiscoveryClient,
HealthIndicator healthIndicator, SidecarProperties sidecarProperties,
ConfigurableEnvironment environment) {
this.sidecarDiscoveryClient = sidecarDiscoveryClient;
this.healthIndicator = healthIndicator;
this.sidecarProperties = sidecarProperties;
this.environment = environment;
}
@Bean
@ConditionalOnEnabledHealthIndicator("nacos-discovery")
public HealthIndicator nacosDiscoveryHealthIndicator(
NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosDiscoveryHealthIndicator(
nacosDiscoveryProperties.namingServiceInstance());
}
@Test
public void getContributorReturnsContributor() throws Exception {
TestDiscoveryHealthIndicator indicator = new TestDiscoveryHealthIndicator("test",
Health.up().build());
DiscoveryCompositeHealthContributor composite = new DiscoveryCompositeHealthContributor(
Arrays.asList(indicator));
HealthIndicator adapted = (HealthIndicator) composite.getContributor("test");
assertThat(adapted).isNotNull();
assertThat(adapted.health()).isSameAs(indicator.health());
}
@Test
public void getContributorWhenMissingReturnsNull() throws Exception {
TestDiscoveryHealthIndicator indicator = new TestDiscoveryHealthIndicator("test",
Health.up().build());
DiscoveryCompositeHealthContributor composite = new DiscoveryCompositeHealthContributor(
Arrays.asList(indicator));
assertThat((HealthIndicator) composite.getContributor("missing")).isNull();
}
@Bean
HealthCheckHandler healthCheckHandler(
ApplicationInfoManager applicationInfoManager,
HealthAggregator healthAggregator,
Map<String, HealthIndicator> healthIndicators) {
return new BootHealthCheckHandler(applicationInfoManager, healthAggregator, healthIndicators);
}
public BootHealthCheckHandler(
ApplicationInfoManager applicationInfoManager,
HealthAggregator aggregator,
Map<String, HealthIndicator> healthIndicators) {
this.applicationInfoManager =
Objects.requireNonNull(applicationInfoManager, "applicationInfoManager");
this.aggregateHealth = new CompositeHealthIndicator(aggregator, healthIndicators);
}
@Bean
@ConditionalOnProperty(
value = "redis.cluster-enabled",
havingValue = "false",
matchIfMissing = true)
public List<HealthIndicator> jedisClientHealthIndicators(
List<RedisClientDelegate> redisClientDelegates) {
return redisClientDelegates.stream()
.filter(it -> it instanceof JedisClientDelegate)
.map(it -> JedisHealthIndicatorFactory.build((JedisClientDelegate) it))
.collect(Collectors.toList());
}
public static HealthIndicator build(JedisClientDelegate client) {
try {
final JedisClientDelegate src = client;
final Field clientAccess = JedisClientDelegate.class.getDeclaredField("jedisPool");
clientAccess.setAccessible(true);
return build((Pool<Jedis>) clientAccess.get(src));
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new BeanCreationException("Error creating Redis health indicator", e);
}
}
public static HealthIndicator build(Pool<Jedis> jedisPool) {
try {
final Pool<Jedis> src = jedisPool;
final Field poolAccess = Pool.class.getDeclaredField("internalPool");
poolAccess.setAccessible(true);
GenericObjectPool<Jedis> internal = (GenericObjectPool<Jedis>) poolAccess.get(jedisPool);
return () -> {
Jedis jedis = null;
Health.Builder health;
try {
jedis = src.getResource();
if ("PONG".equals(jedis.ping())) {
health = Health.up();
} else {
health = Health.down();
}
} catch (Exception ex) {
health = Health.down(ex);
} finally {
if (jedis != null) jedis.close();
}
health.withDetail("maxIdle", internal.getMaxIdle());
health.withDetail("minIdle", internal.getMinIdle());
health.withDetail("numActive", internal.getNumActive());
health.withDetail("numIdle", internal.getNumIdle());
health.withDetail("numWaiters", internal.getNumWaiters());
return health.build();
};
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new BeanCreationException("Error creating Redis health indicator", e);
}
}
@Override
public void afterPropertiesSet() throws Exception {
final Map<String, HealthIndicator> healthIndicators = applicationContext
.getBeansOfType(HealthIndicator.class);
populateHealthIndicators(healthIndicators);
}
protected Status getStatus(StatusAggregator statusAggregator) {
Status status;
Set<Status> statusSet = healthIndicators.values().stream()
.map(HealthIndicator::health).map(Health::getStatus)
.collect(Collectors.toSet());
status = statusAggregator.getAggregateStatus(statusSet);
return status;
}
@Bean
public HealthIndicator healthIndicator() {
return new AbstractHealthIndicator() {
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
builder.up();
}
};
}
@Bean
public HealthIndicator healthIndicator() {
return new AbstractHealthIndicator() {
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
builder.down();
}
};
}