下面列出了怎么用org.springframework.boot.actuate.health.Health.Builder的API类实例代码及写法,或者点击链接到github查看源代码。
private void checkoutAcmHealthIndicator() {
try {
Builder builder = new Builder();
NacosConfigHealthIndicator healthIndicator = new NacosConfigHealthIndicator(
properties.configServiceInstance());
healthIndicator.doHealthCheck(builder);
Builder builder1 = new Builder();
builder1.up();
assertThat(builder.build()).isEqualTo(builder1.build());
}
catch (Exception ignore) {
}
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
Session session = null;
try {
session = cluster.connect();
ResultSet rs = session.execute("SELECT dateof(now()) FROM system.local");
Date date = rs.one().getTimestamp(0);
logger.info("cassandra is working, the time is ", date);
builder.up().withDetail("description", "cassandra is working, the time is " + date);
} catch (Exception e) {
logger.error("cassandra launch has error, {}", e.getMessage());
builder.outOfService().withDetail("description", "cassandra launch has error, " + e.getMessage());
} finally {
if(null != session) {
session.close();
}
}
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
RefreshScope refreshScope = this.scope.getIfAvailable();
if (refreshScope != null) {
Map<String, Exception> errors = new HashMap<>(refreshScope.getErrors());
errors.putAll(this.rebinder.getErrors());
if (errors.isEmpty()) {
builder.up();
}
else {
builder.down();
if (errors.size() == 1) {
builder.withException(errors.values().iterator().next());
}
else {
for (String name : errors.keySet()) {
builder.withDetail(name, errors.get(name));
}
}
}
}
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
PropertySource<?> propertySource = getPropertySource();
builder.up();
if (propertySource instanceof CompositePropertySource) {
List<String> sources = new ArrayList<>();
for (PropertySource<?> ps : ((CompositePropertySource) propertySource)
.getPropertySources()) {
sources.add(ps.getName());
}
builder.withDetail("propertySources", sources);
}
else if (propertySource != null) {
builder.withDetail("propertySources", propertySource.toString());
}
else {
builder.unknown().withDetail("error", "no property sources located");
}
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
try {
// Get the statistical parameter (min/max/avg/latest) etc.
TimesWrapper wrap = this.getLargestMessage();
if (logger.isDebugEnabled()) {
logger.debug("TimeoutsHealth message={}", objectMapper.writeValueAsString(wrap));
}
if (wrap == null) {
HealthUtil.up(builder, "Healthy");
return;
} else if (wrap.getMax() < conf.getTimeoutsThreshold()) {
HealthUtil.up(builder, "Healthy");
} else {
HealthUtil.down(builder, "Method " + wrap.getMetricsName() + " executes " + wrap.getLatest()
+ "ms with a response exceeding the threshold value of `" + conf.getTimeoutsThreshold() + "`ms.");
// When the timeout exception is detected, the exception record
// is cleared.
this.postPropertiesReset(wrap);
}
builder.withDetail("Method", wrap.getMetricsName()).withDetail("Least", wrap.getMin())
.withDetail("Largest", wrap.getMax()).withDetail("Avg", wrap.getAvg()).withDetail("Latest", wrap.getLatest())
.withDetail("Samples", wrap.getSamples()).withDetail("Threshold", conf.getTimeoutsThreshold() + "ms");
} catch (Exception e) {
builder.down(e);
logger.error("Analysis timeouts message failed.", e);
}
}
/** 営業日チェック */
@Bean
HealthIndicator dayIndicator(final Timestamper time, final BusinessDayHandler day) {
return new AbstractHealthIndicator() {
@Override
protected void doHealthCheck(Builder builder) throws Exception {
builder.up();
builder.withDetail("day", day.day())
.withDetail("dayMinus1", day.day(-1))
.withDetail("dayPlus1", day.day(1))
.withDetail("dayPlus2", day.day(2))
.withDetail("dayPlus3", day.day(3));
}
};
}
/** 営業日チェック */
@Bean
HealthIndicator dayIndicator(final Timestamper time, final BusinessDayHandler day) {
return new AbstractHealthIndicator() {
@Override
protected void doHealthCheck(Builder builder) throws Exception {
builder.up();
builder.withDetail("day", day.day())
.withDetail("dayMinus1", day.day(-1))
.withDetail("dayPlus1", day.day(1))
.withDetail("dayPlus2", day.day(2))
.withDetail("dayPlus3", day.day(3));
}
};
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
log.info("Test geolocation service health - start.");
long startTime = System.currentTimeMillis();
Mentor mentor = mentorRepository.findAll().iterator().next();
Point point = mentorUtils.getLocationOfMentor(mentor);
if (point.getLatitude() != 0) {
builder.withDetail("handle", point.toString()).up();
} else {
builder.status("GeocodingError");
}
log.info("Test geolocation service health - end. Duration: " + Long.toString(System.currentTimeMillis() - startTime) + "ms");
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
if (twitter.isAuthenticated()) {
builder.withDetail("handle", twitter.getScreenName()).up();
} else {
builder.status("NotAuthenticated");
}
}
@Override
protected Mono<Health> doHealthCheck(Builder builder) {
return this.vaultOperations
.doWithSession((it) -> it.get().uri("sys/health")
.header(VaultHttpHeaders.VAULT_NAMESPACE, "").exchange())
.flatMap((it) -> it.bodyToMono(VaultHealthImpl.class))
.onErrorResume(WebClientResponseException.class,
VaultReactiveHealthIndicator::deserializeError)
.map((vaultHealthResponse) -> getHealth(builder, vaultHealthResponse));
}
/** 営業日チェック */
@Bean
HealthIndicator dayIndicator(Timestamper time, BusinessDayHandler day) {
return new AbstractHealthIndicator() {
@Override
protected void doHealthCheck(Builder builder) throws Exception {
builder.up();
builder.withDetail("day", day.day())
.withDetail("dayMinus1", day.day(-1))
.withDetail("dayPlus1", day.day(1))
.withDetail("dayPlus2", day.day(2))
.withDetail("dayPlus3", day.day(3));
}
};
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
boolean active = jobExecutor.isActive();
if (active) {
builder = builder.up();
} else {
builder = builder.down();
}
builder.withDetail("jobExecutor", Details.from(jobExecutor));
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
try {
jedisCluster.get("foo");
logger.info("redis is working");
builder.up().withDetail("description", "redis is working");
} catch (Exception e) {
logger.error("redis launch has error, {}", e.getMessage());
builder.outOfService().withDetail("description", "redis launch has error, " + e.getMessage());
}
}
@Override
public Health health() {
Builder builder = Health.unknown();
Status status = getStatus(builder);
return builder.status(status).withDetail("applications", getApplications())
.build();
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
boolean active = jobExecutor.isActive();
if (active) {
builder = builder.up();
} else {
builder = builder.down();
}
builder.withDetail("jobExecutor", Details.from(jobExecutor));
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
int index = 0;
StringBuffer desc = new StringBuffer();
for (String name : this.eventStores.keySet()) {
try {
EventStore<Partition> store = this.eventStores.get(name);
Partition latestPart = store.latest();
if (logger.isDebugEnabled())
logger.debug("Health performance:{}", mapper.writeValueAsString(latestPart));
if (latestPart == null) {
builder.up();
return;
}
// Get partition configuration by current partition.
Partition confPart = this.conf.getPartitions().get(name);
if (confPart == null)
throw new Error("It should not come here. " + name);
// Check threshold.
long threshold = confPart.getValue();
long curVal = latestPart.getValue();
if (this.compare(curVal, threshold) < 0) { // Trigger event.
if (desc.length() > 0) {
desc.append("<br/>");
}
desc.append(name).append(":").append(formatValue(curVal)).append(" exceed the threshold:")
.append(formatValue(confPart.getValue()));
}
// Meaningful field name prefix.
String p = this.compareFieldName();
builder.withDetail("AcqPosition_" + index, name).withDetail("AcqSamples_" + index, latestPart.getSamples())
.withDetail("AcqTime_" + index, latestPart.getFormatTimestamp())
.withDetail(p + "Avg_" + index, formatValue(store.average()))
.withDetail(p + "Lgt_" + index, formatValue(store.largest().getValue()))
.withDetail(p + "Let_" + index, formatValue(store.least().getValue()))
.withDetail(p + "Lat_" + index, formatValue(store.latest().getValue()))
.withDetail(p + "Threshold_" + index, formatValue(threshold));
// All the checks are normal.
if (desc.length() > 0) {
HealthUtil.down(builder, desc.toString());
desc.setLength(0); // Reset.
} else {
builder.up();
}
if (logger.isDebugEnabled()) {
logger.debug("Acquisition unhealthy description:{}", desc);
}
} catch (Exception e) {
builder.down(e);
logger.error("Advanced health check failed.", e);
} finally {
// Increase by 1
++index;
}
}
}
public static Builder up(Builder builder, String desc) {
return build(builder, Status.UP.getCode(), desc);
}
public static Builder down(Builder builder, String desc) {
return build(builder, Status.DOWN.getCode(), desc);
}
public static Builder build(Builder builder, String statusCode, String desc) {
return builder.status(new Status(statusCode, desc));
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
builder.status(Status.UP);
builder.withDetail("hello", "world");
}
private static Health getHealth(Builder builder,
VaultHealthImpl vaultHealthResponse) {
HealthBuilderDelegate.contributeToHealth(vaultHealthResponse, builder);
return builder.build();
}
@Override
protected void doHealthCheck(Builder builder) {
VaultHealth vaultHealthResponse = this.vaultOperations.opsForSys().health();
HealthBuilderDelegate.contributeToHealth(vaultHealthResponse, builder);
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
builder.status(this.up ? Status.UP : Status.DOWN);
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
builder.up().withDetail("name", processEngine.getName());
}
@Override
protected void doHealthCheck(Builder builder) throws Exception {
builder.up().withDetail("name", processEngine.getName());
}