下面列出了怎么用org.springframework.boot.actuate.health.Status的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext context = event.getApplicationContext();
ReadinessCheckListener readinessCheckListener = context
.getBean(ReadinessCheckListener.class);
AppPublisher publisher = context.getBean(AppPublisher.class);
try {
String status = readinessCheckListener.getHealthCheckerStatus() ? Status.UP.toString()
: Status.DOWN.toString();
publisher.getApplication().setAppState(status);
publisher.start();
publisher.register();
} catch (Exception e) {
LOGGER.info("sofa dashboard client register failed.", e);
}
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
Status status = Status.DOWN;
String errorDetails = null;
if (getSolrTemplate() != null && getSolrTemplate().getSolrClient() != null) {
try {
SolrClient solrClient = getSolrTemplate().getSolrClient();
SolrQuery q = new SolrQuery("*:*");
q.setRows(0);
QueryResponse response = solrClient.query(q);
if (response.getStatus() == 0) {
status = Status.UP;
if (response.getResults() != null) {
builder.withDetail("numDocs", response.getResults().getNumFound());
}
}
} catch (Exception e) {
errorDetails = e.getMessage();
}
}
builder.status(status);
if (errorDetails != null) {
builder.withDetail("error", errorDetails);
}
}
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
}
@Test
public void shouldReturnHealthState() {
ReactiveVaultTemplate vaultTemplate = new ReactiveVaultTemplate(
TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
ClientHttpConnectorFactory.create(new ClientOptions(),
Settings.createSslConfiguration()),
() -> Mono.just(Settings.token()));
VaultReactiveHealthIndicator healthIndicator = new VaultReactiveHealthIndicator(
vaultTemplate);
healthIndicator.doHealthCheck(Health.up()).as(StepVerifier::create)
.consumeNextWith(actual -> {
assertThat(actual.getStatus()).isEqualTo(Status.UP);
}).verifyComplete();
}
private void retrieveHealthData(ApplicationInstance instance) {
instance.getActuatorEndpoint("health").ifPresent(link -> {
logger.debug("Retrieving [HEALTH] data for {}", instance.getId());
this.webClient.get().uri(link.getHref()).retrieve().bodyToMono(HealthWrapper.class)
.defaultIfEmpty(new HealthWrapper(Status.UNKNOWN, new HashMap<>()))
.map(HealthWrapper::getHealth)
.doOnError(exception -> {
logger.debug("Could not retrieve health information for [{}]", link.getHref(), exception);
this.publisher.publishEvent(new ApplicationInstanceHealthDataRetrievalFailed(instance));
})
.subscribe(healthInfo -> {
logger.debug("Retrieved health information for application instance [{}]", instance.getId());
this.publisher.publishEvent(new ApplicationInstanceHealthDataRetrieved(instance, healthInfo));
});
});
}
@Test
public void mockCacheServerHealthCheckWithServerLoadDetails() {
Health health = this.healthIndicator.health();
assertThat(health).isNotNull();
assertThat(health.getStatus()).isEqualTo(Status.UP);
Map<String, Object> healthDetails = health.getDetails();
assertThat(healthDetails).isNotNull();
assertThat(healthDetails).isNotEmpty();
assertThat(healthDetails).containsEntry("geode.cache.server.count", 1);
assertThat(healthDetails).containsEntry("geode.cache.server.0.port", 48484);
assertThat(healthDetails).containsEntry("geode.cache.server.0.load.connection-load", 0.65f);
assertThat(healthDetails).containsEntry("geode.cache.server.0.load.load-per-connection", 0.35f);
assertThat(healthDetails).containsEntry("geode.cache.server.0.load.load-per-subscription-connection", 0.75f);
assertThat(healthDetails).containsEntry("geode.cache.server.0.load.subscription-connection-load", 0.55f);
assertThat(healthDetails).containsEntry("geode.cache.server.0.metrics.client-count", 21);
assertThat(healthDetails).containsEntry("geode.cache.server.0.metrics.max-connection-count", 800);
assertThat(healthDetails).containsEntry("geode.cache.server.0.metrics.open-connection-count", 400);
assertThat(healthDetails).containsEntry("geode.cache.server.0.metrics.subscription-connection-count", 200);
}
@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();
}
private void assertHealthInfoRetrievalSucceeded(List<ApplicationInstance> applicationInstances) {
String logOutput = this.outputCapture.toString();
assertThat(logOutput).contains("Retrieving [HEALTH] data for all application instances");
applicationInstances.forEach((applicationInstance) -> {
assertThat(logOutput).contains(String.format("Retrieving [HEALTH] data for %s", applicationInstance.getId()));
assertThat(logOutput).contains(String.format("Retrieved health information for application instance [%s]",
applicationInstance.getId()));
});
verify(this.applicationEventPublisher, times(applicationInstances.size()))
.publishEvent(this.applicationEventArgumentCaptor.capture());
verifyNoMoreInteractions(this.applicationEventPublisher);
List<ApplicationInstanceHealthDataRetrieved> healthInfoRetrievals =
(List) this.applicationEventArgumentCaptor.getAllValues();
healthInfoRetrievals.forEach(healthInfoRetrieved -> {
ApplicationInstance instance = (ApplicationInstance) healthInfoRetrieved.getSource();
assertThat(healthInfoRetrieved).isNotNull();
assertThat(healthInfoRetrieved.getHealth()).isNotNull();
assertThat(healthInfoRetrieved.getHealth().getStatus()).isEqualTo(Status.UP);
assertThat(applicationInstances).contains(instance);
});
}
@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());
});
}
@Test
public void whenShutdown_thenHazelcastJetDown() {
this.contextRunner.run((context) -> {
context.getBean(JetInstance.class).shutdown();
assertThat(context).hasSingleBean(HazelcastJetHealthIndicator.class);
Health health = context.getBean(HazelcastJetHealthIndicator.class).health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
});
}
public UpdateApplicationInstanceHealth(String id, Status healthStatus) {
Assert.notNull(id, "id must not be null!");
Assert.notNull(healthStatus, "healthStatus must not be null!");
this.id = id;
this.healthStatus = healthStatus;
}
@Test
public void whenIsRunningFalse_thenHazelcastJetDown() {
mockJet(false);
Health health = new HazelcastJetHealthIndicator(jet).health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertDetails(health);
}
@Test
public void healthIndicatorUpMultipleCallsTest() throws Exception {
try (ConfigurableApplicationContext context = singleStream("ApplicationHealthTest-xyz")) {
int callsToPerform = 5;
for (int i = 0; i < callsToPerform; i++) {
receive(context,
Lists.newArrayList(new ProducerRecord<>("in", "{\"id\":\"123\"}"),
new ProducerRecord<>("in", "{\"id\":\"123\"}")),
Status.UP, "out");
}
}
}
private void assertHealthInfoRetrievalSucceeded(ApplicationInstance instance) {
verify(this.applicationEventPublisher).publishEvent(this.applicationEventArgumentCaptor.capture());
verifyNoMoreInteractions(this.applicationEventPublisher);
assertThat(this.outputCapture.toString())
.contains(String.format("Retrieved health information for application instance [%s]", instance.getId()));
ApplicationInstanceHealthDataRetrieved healthInfoRetrieved =
(ApplicationInstanceHealthDataRetrieved) this.applicationEventArgumentCaptor.getValue();
assertThat(healthInfoRetrieved).isNotNull();
assertThat(healthInfoRetrieved.getHealth()).isNotNull();
assertThat(healthInfoRetrieved.getHealth().getStatus()).isEqualTo(Status.UP);
assertThat(healthInfoRetrieved.getHealth().getDetails()).isNotNull();
assertThat(healthInfoRetrieved.getSource()).isEqualTo(instance);
}
@Test
public void defaultStatusWorks() {
when(this.repository.findOne(anyString(), anyString(), Mockito.<String>isNull(),
anyBoolean())).thenReturn(this.environment);
assertThat(this.indicator.health().getStatus()).as("wrong default status")
.isEqualTo(Status.UP);
}
@Override
public InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus instanceStatus) {
Status status = myHealthIndicator.health().getStatus();
if(Status.UP.equals(status)){
return InstanceInfo.InstanceStatus.UP;
}
return InstanceInfo.InstanceStatus.DOWN;
}
@Test
public void testHealthCheckOther() {
ClusterHealth clusterHealth = createClusterHealth("other");
when(clusterService.checkClusterHealth(DEFAULT_CLUSTER_NAME)).thenReturn(clusterHealth);
Health health = indicator.health();
assertEquals(Status.DOWN, health.getStatus());
}
@Test
public void deveRetornarDownQuandoClusterNãoTemConexão() throws Exception {
given(admin.cluster().health(anyObject()).actionGet().getStatus()).willReturn(RED);
assertThat(indicator.health().getStatus(), is(Status.DOWN));
assertThat(indicator.health().getDetails().get("status"), is(RED));
}
@Test
public void shouldReturnUpStatusWithoutServices() {
when(discoveryClient.description()).thenReturn("Mocked Service Discovery Client");
when(discoveryClient.getServices()).thenReturn(Flux.empty());
Health expectedHealth = Health.status(new Status(Status.UP.getCode(), ""))
.withDetail("services", emptyList()).build();
indicator.onApplicationEvent(new InstanceRegisteredEvent<>(this, null));
Mono<Health> health = indicator.health();
assertThat(indicator.getName()).isEqualTo("Mocked Service Discovery Client");
StepVerifier.create(health).expectNext(expectedHealth).expectComplete().verify();
}
@Test
public void shouldReportSealedService() {
when(this.healthResponse.isInitialized()).thenReturn(true);
when(this.healthResponse.isSealed()).thenReturn(true);
Health health = this.healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat(health.getDetails()).containsEntry("state", "Vault sealed");
}
@Test
public void testStatusIsUpWhenCatalogAndDiscoveryAreAvailable() {
DiscoveryClient discoveryClient = mock(DiscoveryClient.class);
when(discoveryClient.getInstances(CoreService.API_CATALOG.getServiceId())).thenReturn(
Collections.singletonList(new DefaultServiceInstance(CoreService.API_CATALOG.getServiceId(), "host", 10014, true)));
when(discoveryClient.getInstances(CoreService.DISCOVERY.getServiceId())).thenReturn(
Collections.singletonList(new DefaultServiceInstance(CoreService.DISCOVERY.getServiceId(), "host", 10011, true)));
when(discoveryClient.getInstances(ZOSMF)).thenReturn(
Collections.singletonList(new DefaultServiceInstance(ZOSMF, "host", 10050, true)));
GatewayHealthIndicator gatewayHealthIndicator = new GatewayHealthIndicator(discoveryClient, authConfigurationProperties);
Health.Builder builder = new Health.Builder();
gatewayHealthIndicator.doHealthCheck(builder);
assertEquals(Status.UP, builder.build().getStatus());
}
/**
* To start tomcat and register service
*
* @return this instance to next command
* @throws IOException problem with socket
* @throws LifecycleException Tomcat exception
*/
public VirtualService start() throws IOException, LifecycleException {
// start Tomcat to get listening port
tomcat.start();
instanceId = InetAddress.getLocalHost().getHostName() + ":" + serviceId + ":" + getPort();
// register into discovery service and start heart beating
register(Status.UP.toString());
healthService = new HealthService(renewalIntervalInSecs);
started = true;
return this;
}
@Test
public void retornaDownParaExcecoes() throws Exception {
given(es.indexExists(PORTAL_DE_SERVICOS_INDEX)).willThrow(new RuntimeException("boom"));
Health health = indicator.health();
assertThat(health.getStatus(), is(Status.DOWN));
assertThat(health.getDetails().get(PORTAL_DE_SERVICOS_INDEX), is("exception"));
assertThat(health.getDetails().get("error"), is("java.lang.RuntimeException: boom"));
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setStatus(HttpStatus.SC_OK);
resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
final Status status = healthService == null ? Status.UNKNOWN : healthService.getStatus();
resp.getWriter().print("{\"status\":\"" + status + "\"}");
resp.getWriter().close();
}
@Test
public void whenCheckMethodReturnsOtherThanZero_thenHealthMethodReturnsStatusDOWN() {
HealthCheck healthCheck = Mockito.spy(new HealthCheck());
when(healthCheck.check()).thenReturn(-1);
Health health = healthCheck.health();
assertThat(health.getStatus(), is(Status.DOWN));
}
@Test
public void testStatusIsUpWhenGatewayIsAvailable() {
when(discoveryClient.getInstances(CoreService.GATEWAY.getServiceId())).thenReturn(
Collections.singletonList(
new DefaultServiceInstance(CoreService.GATEWAY.getServiceId(), "host", 10010, true)));
apiCatalogHealthIndicator.doHealthCheck(builder);
assertEquals(Status.UP, builder.build().getStatus());
}
@Test
public void testStatusIsDownWhenGatewayIsNotAvailable() {
when(discoveryClient.getInstances(CoreService.GATEWAY.getServiceId())).thenReturn(Collections.emptyList());
apiCatalogHealthIndicator.doHealthCheck(builder);
assertEquals(Status.DOWN, builder.build().getStatus());
}
@Test
public void deveRetornarDownQuandoClusterTemPoucosNodos() throws Exception {
given(admin.cluster().health(anyObject()).actionGet().getStatus()).willReturn(YELLOW);
assertThat(indicator.health().getStatus(), is(Status.DOWN));
assertThat(indicator.health().getDetails().get("status"), is(YELLOW));
}
@Test
public void testSentinelNotEnabled() {
when(sentinelProperties.isEnabled()).thenReturn(false);
Health health = sentinelHealthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails().get("enabled")).isEqualTo(false);
}
@Test
public void testSentinelDashboardConfiguredFailed() throws Exception {
when(sentinelProperties.isEnabled()).thenReturn(true);
SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080");
when(heartbeatSender.sendHeartbeat()).thenReturn(false);
Health health = sentinelHealthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat(health.getDetails().get("dashboard")).isEqualTo(
new Status(Status.DOWN.getCode(), "localhost:8080 can't be connected"));
}