下面列出了怎么用org.springframework.boot.actuate.health.Health的API类实例代码及写法,或者点击链接到github查看源代码。
private BiConsumer<Region<?, ?>, Health.Builder> withRegionExpirationPolicyDetails() {
return (region, builder) -> {
if (isRegionAttributesPresent(region)) {
String regionName = region.getName();
RegionAttributes<?, ?> regionAttributes = region.getAttributes();
ExpirationAttributes entryTimeToLive = regionAttributes.getEntryTimeToLive();
if (entryTimeToLive != null) {
builder.withDetail(cacheRegionExpirationKey(regionName, "entry.ttl.action"), String.valueOf(entryTimeToLive.getAction()))
.withDetail(cacheRegionExpirationKey(regionName, "entry.ttl.timeout"), entryTimeToLive.getTimeout());
}
ExpirationAttributes entryIdleTimeout = regionAttributes.getEntryIdleTimeout();
if (entryIdleTimeout != null) {
builder.withDetail(cacheRegionExpirationKey(regionName, "entry.tti.action"), String.valueOf(entryIdleTimeout.getAction()))
.withDetail(cacheRegionExpirationKey(regionName, "entry.tti.timeout"), entryIdleTimeout.getTimeout());
}
}
};
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
// Just return "UP" or "DOWN"
String status = namingService.getServerStatus();
// Set the status to Builder
builder.status(status);
switch (status) {
case "UP":
builder.up();
break;
case "DOWN":
builder.down();
break;
default:
builder.unknown();
break;
}
}
@Override
public Health health() {
try {
URL url =
new URL("http://greglturnquist.com/learning-spring-boot");
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
int statusCode = conn.getResponseCode();
if (statusCode >= 200 && statusCode < 300) {
return Health.up().build();
} else {
return Health.down()
.withDetail("HTTP Status Code", statusCode)
.build();
}
} catch (IOException e) {
return Health.down(e).build();
}
}
@Override
protected void doHealthCheck(final Health.Builder builder) {
HealthCheck check = this.influxDBClient.health();
switch (check.getStatus()) {
case PASS:
builder.up();
break;
case FAIL:
builder.down();
break;
default:
builder.unknown();
}
builder
.withDetail("status", check.getStatus())
.withDetail("message", check.getMessage());
}
@Override
public Health health() {
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if (hour > 12) {
return Health
.outOfService()
.withDetail("reason",
"I'm out of service after lunchtime")
.withDetail("hour", hour)
.build();
}
if (Math.random() < 0.1) {
return Health
.down()
.withDetail("reason", "I break 10% of the time")
.build();
}
return Health
.up()
.withDetail("reason", "All is good!")
.build();
}
@Override
public Health health() {
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if (hour > 12) {
return Health
.outOfService()
.withDetail("reason",
"I'm out of service after lunchtime")
.withDetail("hour", hour)
.build();
}
if (Math.random() < 0.1) {
return Health
.down()
.withDetail("reason", "I break 10% of the time")
.build();
}
return Health
.up()
.withDetail("reason", "All is good!")
.build();
}
@Override
public Health health() {
try {
URL url =
new URL("http://greglturnquist.com/learning-spring-boot");
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
int statusCode = conn.getResponseCode();
if (statusCode >= 200 && statusCode < 300) {
return Health.up().build();
} else {
return Health.down()
.withDetail("HTTP Status Code", statusCode)
.build();
}
} catch (IOException e) {
return Health.down(e).build();
}
}
@Override
public Health health() {
try {
Health.Builder builder = Health.up();
if (leaderManager == null) {
builder.withDetail("run", queue.isRunning());
} else {
builder.withDetail("run", queue.isRunning()).withDetail("isMaster", leaderManager.isLeader());
}
return builder
.withDetail("isCluster", redisQueueProperties.isCluster())
.withDetail("bucketSize", redisQueueProperties.getBucketSize())
.withDetail("prefix", redisQueueProperties.getPrefix())
.withDetail("namespace", ServerNode.NAMESPACE)
.build();
} catch (Exception e) {
return Health.down(e).build();
}
}
private Mono<Health> doHealthCheck() {
// @formatter:off
return Mono.justOrEmpty(this.discoveryClient)
.flatMapMany(ReactiveDiscoveryClient::getServices)
.collectList()
.defaultIfEmpty(emptyList())
.map(services -> {
ReactiveDiscoveryClient client = this.discoveryClient;
String description = (this.properties.isIncludeDescription())
? client.description() : "";
return Health.status(new Status("UP", description))
.withDetail("services", services).build();
})
.onErrorResume(exception -> {
this.log.error("Error", exception);
return Mono.just(Health.down().withException(exception).build());
});
// @formatter:on
}
static void contributeToHealth(VaultHealth healthResponse, Health.Builder builder) {
if (!healthResponse.isInitialized()) {
builder.down().withDetail("state", "Vault uninitialized");
}
else if (healthResponse.isSealed()) {
builder.down().withDetail("state", "Vault sealed");
}
else if (healthResponse.isStandby()) {
builder.up().withDetail("state", "Vault in standby");
}
else if (healthResponse.isPerformanceStandby()) {
builder.up().withDetail("state", "Vault in performance standby");
}
else if (healthResponse.isRecoveryReplicationSecondary()) {
builder.up().withDetail("state",
"Vault in recovery replication secondary mode");
}
else {
builder.up();
}
if (StringUtils.hasText(healthResponse.getVersion())) {
builder.withDetail("version", healthResponse.getVersion());
}
}
@Test
void shouldReturnKnownContributor() {
ReactiveDiscoveryHealthIndicator indicator = mock(
ReactiveDiscoveryHealthIndicator.class);
Health health = Health.up().build();
when(indicator.getName()).thenReturn("known");
when(indicator.health()).thenReturn(Mono.just(health));
ReactiveDiscoveryCompositeHealthContributor healthContributor = new ReactiveDiscoveryCompositeHealthContributor(
singletonList(indicator));
assertThat(healthContributor.getContributor("known")).isNotNull();
Iterator<NamedContributor<ReactiveHealthContributor>> iterator = healthContributor
.iterator();
assertThat(iterator.hasNext()).isTrue();
NamedContributor<ReactiveHealthContributor> contributor = iterator.next();
assertThat(contributor).isNotNull();
assertThat(contributor.getName()).isEqualTo("known");
assertThat(contributor.getContributor()).isNotNull();
assertThat(contributor.getContributor())
.isInstanceOf(ReactiveHealthIndicator.class);
ReactiveHealthIndicator healthIndicator = (ReactiveHealthIndicator) contributor
.getContributor();
StepVerifier.create(healthIndicator.getHealth(true)).expectNext(health)
.expectComplete().verify();
}
@Test
public void shouldIndicateDownWhenSomeEventSourceIsFailed() {
// given
MessageReceiverEndpointHealthIndicator healthCheck = new MessageReceiverEndpointHealthIndicator();
EventSource mockEventSource = mock(EventSource.class);
when(mockEventSource.getChannelName()).thenReturn("some-stream");
MessageReceiverNotification messageEndpointNotification = builder()
.withStatus(FAILED)
.withMessage("some message")
.withChannelName("some-stream")
.build();
healthCheck.on(messageEndpointNotification);
// when
Health health = healthCheck.health();
// then
assertThat(health.getStatus(), is(Status.DOWN));
assertThat(health.getDetails(), hasEntry("message", "some message"));
assertThat(health.getDetails(), hasEntry("channelName", "some-stream"));
}
@Test
public void consumerCreationFailsFirstTime() {
final List<PartitionInfo> partitions = partitions(new Node(0, null, 0));
topicsInUse.put(TEST_TOPIC, new KafkaMessageChannelBinder.TopicInformation(
"foo-healthIndicator", partitions, false));
org.mockito.BDDMockito.given(consumerFactory.createConsumer())
.willThrow(KafkaException.class).willReturn(consumer);
Health health = indicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
health = indicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP);
org.mockito.Mockito.verify(this.consumerFactory, Mockito.times(2))
.createConsumer();
}
/**
* 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();
};
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
builder.up();
NacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory
.getSingleton();
for (NamingService namingService : nacosServiceFactory.getNamingServices()) {
if (namingService instanceof NacosServiceMetaData) {
NacosServiceMetaData nacosServiceMetaData = (NacosServiceMetaData) namingService;
Properties properties = nacosServiceMetaData.getProperties();
builder.withDetail(
JSON.toJSONString(
PropertiesUtils.extractSafeProperties(properties)),
namingService.getServerStatus());
}
if (!namingService.getServerStatus().equalsIgnoreCase(UP_STATUS)) {
builder.down();
}
}
}
@Override
public Health health() {
final SapClient sapClient = new SapClient("SAPCLIENT-NUMBER"); // adjust SAP client to your respective S/4HANA system
final String problem = checkForProblem(sapClient);
if (problem != null) {
return Health.down().withDetail("Error", problem).build();
}
return Health.up().build();
}
@Override
protected void doHealthCheck(Health.Builder builder) {
if (jetInstance.getHazelcastInstance().getLifecycleService().isRunning()) {
builder.up();
} else {
builder.down();
}
builder.withDetail("name", jetInstance.getName()).withDetail("uuid",
jetInstance.getHazelcastInstance().getLocalEndpoint().getUuid().toString());
}
@Test
public void whenAutoConfigured_thenHazelcastJetUp() {
this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(JetInstance.class).hasSingleBean(HazelcastJetHealthIndicator.class);
JetInstance jet = context.getBean(JetInstance.class);
Health health = context.getBean(HazelcastJetHealthIndicator.class).health();
assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails())
.containsOnlyKeys("name", "uuid")
.containsEntry("name", jet.getName())
.containsEntry("uuid", jet.getHazelcastInstance().getLocalEndpoint().getUuid().toString());
});
}
@Override
protected void doHealthCheck(Health.Builder builder) {
if (getGemFireCache().isPresent()) {
Set<Region<?, ?>> rootRegions = getGemFireCache()
.map(GemFireCache::rootRegions)
.orElseGet(Collections::emptySet);
builder.withDetail("geode.cache.regions", rootRegions.stream()
.filter(Objects::nonNull)
.map(Region::getFullPath)
.sorted()
.collect(Collectors.toList()));
builder.withDetail("geode.cache.regions.count", rootRegions.stream().filter(Objects::nonNull).count());
rootRegions.stream()
.filter(Objects::nonNull)
.forEach(region -> getGemfireRegionHealthIndicatorConsumers().accept(region, builder));
builder.up();
return;
}
builder.unknown();
}
@Test
public void kafkaBinderIsUp() {
final List<PartitionInfo> partitions = partitions(new Node(0, null, 0));
topicsInUse.put(TEST_TOPIC, new KafkaMessageChannelBinder.TopicInformation(
"group1-healthIndicator", partitions, false));
org.mockito.BDDMockito.given(consumer.partitionsFor(TEST_TOPIC))
.willReturn(partitions);
Health health = indicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP);
}
@Override
public Health health() {
int errorCode = appHealthCheck();
if (errorCode != UP) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
}
@Override
public Mono<Integer> check(String serviceName) {
return Flux.fromIterable(healthIndicators)
.flatMap(healthIndicator -> healthIndicator
.health().map(Health::getStatus))
.all(status -> status == Status.UP)
.map(result -> result ? SERVING_STATUS : DOWN_STATUS);
}
@Override
public Health health() {
HealthGrpc.HealthImplBase healthService = (HealthGrpc.HealthImplBase) healthStatusManager
.getHealthService();
HealthCheckRequest healthcheckRequest = HealthCheckRequest.newBuilder().setService(serviceName).build();
HealthStreamObserver healthStreamObserver = new HealthStreamObserver();
healthService.check(healthcheckRequest, healthStreamObserver);
return healthStreamObserver.getHealth();
}
@Test
public void shouldReportRecoveryReplication() {
when(this.healthResponse.isInitialized()).thenReturn(true);
when(this.healthResponse.isRecoveryReplicationSecondary()).thenReturn(true);
Health health = this.healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails()).containsEntry("state",
"Vault in recovery replication secondary mode");
}
@Override
public Health health() {
long size = repo.count();
if(size <= QUOTA_MAX_SIZE)
return Health.up().withDetail("quota.entries", size).build();
else
return Health.down().withDetail("quota.entries", size).withException(new QuotaException("Quota Exceeded. Max allow: " + QUOTA_MAX_SIZE + ". See your Administrator for Quota policies.")).build();
}
@Test
public void shouldReportStandbyService() {
when(this.healthResponse.isInitialized()).thenReturn(true);
when(this.healthResponse.isStandby()).thenReturn(true);
Health health = this.healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails()).containsEntry("state", "Vault in standby");
}
@Override public Health health() {
int errorCode = check();
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode) .build();
}
return Health.up().build();
}
@Override
public Health health() {
Health.Builder builder;
if (inRotation) {
builder = Health.up();
} else {
builder = Health.down();
}
return builder.withDetail("host", host).build();
}
@Override
public Health health() {
try {
long count = repository.count();
if (count >= 0) {
return Health.up().withDetail("count", count).build();
} else {
return Health.unknown().withDetail("count", count).build();
}
} catch (Exception e) {
return Health.down(e).build();
}
}
@Override
protected synchronized void doHealthCheck(Health.Builder builder) throws Exception {
if (checksCompleted == atlasStorageUpdaters.size()) {
builder.up();
} else {
builder.down();
}
builder.withDetail("checksCompleted", checksCompleted);
builder.withDetail("checksExpected", atlasStorageUpdaters.size());
}