spring boot的健康检查HealthIndicators实战

目录
  • springboot 健康检查HealthIndicators
  • springboot health indicator原理及其使用
    • 作用
    • 自动配置的Health Indicator
    • 分组
    • 如何管理Health Indicator
    • RedisHealthIndicator源码解析
    • 自定义Indicator

springboot 健康检查HealthIndicators

想提供自定义健康信息,你可以注册实现了HealthIndicator接口的Spring beans。

你需要提供一个health()方法的实现,并返回一个Health响应。

Health响应需要包含一个status和可选的用于展示的详情。

import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class MyHealth implements HealthIndicator {
@Override
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
} r
eturn Health.up().build();
}
}

除了Spring Boot预定义的Status类型,Health也可以返回一个代表新的系统状态的自定义Status。

在这种情况下,需要提供一个HealthAggregator接口的自定义实现,或使用management.health.status.order属性配置默认的实现。

例如,假设一个新的,代码为FATAL的Status被用于你的一个HealthIndicator实现中。 为了配置严重程度, 你需要将下面的配

置添加到application属性文件中:

management.health.status.order: DOWN, OUT_OF_SERVICE, UNKNOWN, UP

如果使用HTTP访问health端点, 你可能想要注册自定义的status, 并使用HealthMvcEndpoint进行映射。 例如, 你可以将

FATAL映射为HttpStatus.SERVICE_UNAVAILABLE。

springboot health indicator原理及其使用

作用

sping boot health 可以通过暴露的接口来提供系统及其系统组件是否可用。默认通过/health来访问。返回结果如下:

{
  "status": "UP",
  "discoveryComposite": {
    "description": "Spring Cloud Eureka Discovery Client",
    "status": "UP",
    "discoveryClient": {
      "description": "Spring Cloud Eureka Discovery Client",
      "status": "UP",
      "services": [
        "..."
      ]
    },
    "eureka": {
      "description": "Remote status from Eureka server",
      "status": "UP",
      "applications": {
        "AOMS-MOBILE": 1,
        "DATA-EXCHANGE": 1,
        "CLOUD-GATEWAY": 2,
        "AOMS": 1,
        "AOMS-AIIS": 0,
        "AOMS-EUREKA": 2
      }
    }
  },
  "diskSpace": {
    "status": "UP",
    "total": 313759301632,
    "free": 291947081728,
    "threshold": 10485760
  },
  "refreshScope": {
    "status": "UP"
  },
  "hystrix": {
    "status": "UP"
  }
}

状态说明:

  • UNKNOWN:未知状态,映射HTTP状态码为503
  • UP:正常,映射HTTP状态码为200
  • DOWN:失败,映射HTTP状态码为503
  • OUT_OF_SERVICE:不能对外提供服务,但是服务正常。映射HTTP状态码为200

注意:UNKNOWN,DOWN,OUT_OF_SERVICE在为微服务环境下会导致注册中心中的实例也为down状态,请根据具体的业务来正确使用状态值。

自动配置的Health Indicator

自动配置的HealthIndicator主要有以下内容:

Key Name Description
cassandra CassandraDriverHealthIndicator Checks that a Cassandra database is up.
couchbase CouchbaseHealthIndicator Checks that a Couchbase cluster is up.
datasource DataSourceHealthIndicator Checks that a connection to DataSource can be obtained.
diskspace DiskSpaceHealthIndicator Checks for low disk space.
elasticsearch ElasticsearchRestHealthIndicator Checks that an Elasticsearch cluster is up.
hazelcast HazelcastHealthIndicator Checks that a Hazelcast server is up.
influxdb InfluxDbHealthIndicator Checks that an InfluxDB server is up.
jms JmsHealthIndicator Checks that a JMS broker is up.
ldap LdapHealthIndicator Checks that an LDAP server is up.
mail MailHealthIndicator Checks that a mail server is up.
mongo MongoHealthIndicator Checks that a Mongo database is up.
neo4j Neo4jHealthIndicator Checks that a Neo4j database is up.
ping PingHealthIndicator Always responds with UP.
rabbit RabbitHealthIndicator Checks that a Rabbit server is up.
redis RedisHealthIndicator Checks that a Redis server is up.
solr SolrHealthIndicator Checks that a Solr server is up.

分组

可以通过一个别名来启用一组指标的访问。配置的格式如下:

management.endpoint.health.group.<name>
//demo:
management.endpoint.health.group.mysys.include=db,redis,mail
management.endpoint.health.group.custom.exclude=rabbit

如何管理Health Indicator

开启

可以通过management.health.key.enabled来启用key对应的indicator。例如:

management.health.db.enabled=true

关闭

management.health.db.enabled=false

RedisHealthIndicator源码解析

下面,通过RedisHealthIndicator源码来为什么可以这么写。

代码结构

自动配置的health indicator有HealthIndicator和HealthIndicatorAutoConfiguration两部分组成。

HealthIndicator所在包在org.springframework.boot.actuate,

HealthIndicatorAutoConfiguration所在包在org.springframework.boot.actuate.autoconfigure下

//RedisHealthIndicator.java
public class RedisHealthIndicator extends AbstractHealthIndicator {
	static final String VERSION = "version";
	static final String REDIS_VERSION = "redis_version";
	private final RedisConnectionFactory redisConnectionFactory;
	public RedisHealthIndicator(RedisConnectionFactory connectionFactory) {
		super("Redis health check failed");
		Assert.notNull(connectionFactory, "ConnectionFactory must not be null");
		this.redisConnectionFactory = connectionFactory;
	}
	@Override
	protected void doHealthCheck(Health.Builder builder) throws Exception {
		RedisConnection connection = RedisConnectionUtils
				.getConnection(this.redisConnectionFactory);
		try {
			if (connection instanceof RedisClusterConnection) {
				ClusterInfo clusterInfo = ((RedisClusterConnection) connection)
						.clusterGetClusterInfo();
				builder.up().withDetail("cluster_size", clusterInfo.getClusterSize())
						.withDetail("slots_up", clusterInfo.getSlotsOk())
						.withDetail("slots_fail", clusterInfo.getSlotsFail());
			}
			else {
				Properties info = connection.info();
				builder.up().withDetail(VERSION, info.getProperty(REDIS_VERSION));
			}
		}
		finally {
			RedisConnectionUtils.releaseConnection(connection,
					this.redisConnectionFactory);
		}
	}
}

主要实现doHealthCheck方法来实现具体的判断逻辑。注意,操作完成后在finally中释放资源。

在父类AbstractHealthIndicator中,对doHealthCheck进行了try catch,如果出现异常,则返回Down状态。

 //AbstractHealthIndicator.java
 @Override
 public final Health health() {
  Health.Builder builder = new Health.Builder();
  try {
   doHealthCheck(builder);
  }
  catch (Exception ex) {
   if (this.logger.isWarnEnabled()) {
    String message = this.healthCheckFailedMessage.apply(ex);
    this.logger.warn(StringUtils.hasText(message) ? message : DEFAULT_MESSAGE,
      ex);
   }
   builder.down(ex);
  }
  return builder.build();
 }

RedisHealthIndicatorAutoConfiguration完成RedisHealthIndicator的自动配置

@Configuration
@ConditionalOnClass(RedisConnectionFactory.class)
@ConditionalOnBean(RedisConnectionFactory.class)
@ConditionalOnEnabledHealthIndicator("redis")
@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
@AutoConfigureAfter({ RedisAutoConfiguration.class,
  RedisReactiveHealthIndicatorAutoConfiguration.class })
public class RedisHealthIndicatorAutoConfiguration extends
  CompositeHealthIndicatorConfiguration<RedisHealthIndicator, RedisConnectionFactory> {
 private final Map<String, RedisConnectionFactory> redisConnectionFactories;
 public RedisHealthIndicatorAutoConfiguration(
   Map<String, RedisConnectionFactory> redisConnectionFactories) {
  this.redisConnectionFactories = redisConnectionFactories;
 }
 @Bean
 @ConditionalOnMissingBean(name = "redisHealthIndicator")
 public HealthIndicator redisHealthIndicator() {
  return createHealthIndicator(this.redisConnectionFactories);
 }
}

重点说明ConditionalOnEnabledHealthIndicator:如果management.health..enabled为true,则生效。

CompositeHealthIndicatorConfiguration 中会通过HealthIndicatorRegistry注册创建的HealthIndicator

自定义Indicator

@Component
@ConditionalOnProperty(name="spring.dfs.http.send-url")
@Slf4j
public class DfsHealthIndicator implements HealthIndicator {
    @Value("${spring.dfs.http.send-url}")
    private String dsfSendUrl;
    @Override
    public Health health() {
        log.debug("正在检查dfs配置项...");
        log.debug("dfs 请求地址:{}",dsfSendUrl);
        Health.Builder up = Health.up().withDetail("url", dsfSendUrl);
        try {
            HttpUtils.telnet(StringUtils.getIpFromUrl(dsfSendUrl),StringUtils.getPortFromUrl(dsfSendUrl));
            return up.build();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("DFS配置项错误或网络超时");
            return up.withException(e).build();
        }
    }
}

返回值:

{
    "dfs": {
    "status": "UP",
    "url": "10.254.131.197:8088",
    "error": "java.net.ConnectException: Connection refused (Connection refused)"
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot实现项目健康检查与监控

    Spring Boot 最主要的特性就是AutoConfig(自动配置),而对于我们这些使用者来说也就是各种starter, Spring Boot-Actuator 也提供了starter,为我们自动配置,在使用上我们只需要添加starter到我们的依赖中,然后启动项目即可. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-ac

  • 详解SpringBoot健康检查的实现原理

    SpringBoot自动装配的套路,直接看 spring.factories 文件,当我们使用的时候只需要引入如下依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> 然后在 org.springframework.boot.sprin

  • SpringBoot actuator 健康检查不通过的解决方案

    SpringBoot actuator 健康检查不通过 今天遇到有个服务能够注册成功,但是健康检查不通过,通过浏览器访问健康检查的url,chrome的network一直显示pending,说明这个请求提交了,但是得不到返回,卡住了. 原来以为健康检查就是检查服务端口下的/health这个请求本身是否能正常返回,其实不是. 所谓健康检查是有很多检查项的,springboot中继承AbstractHealthIndicator的类,比如DataSourceHealthIndicator Redis

  • spring boot的健康检查HealthIndicators实战

    目录 springboot 健康检查HealthIndicators springboot health indicator原理及其使用 作用 自动配置的Health Indicator 分组 如何管理Health Indicator RedisHealthIndicator源码解析 自定义Indicator springboot 健康检查HealthIndicators 想提供自定义健康信息,你可以注册实现了HealthIndicator接口的Spring beans. 你需要提供一个heal

  • Spring Cloud Admin健康检查 邮件、钉钉群通知的实现

    本文主要介绍了Spring Cloud Admin的使用,分享给大家,具体如下: 源码地址:https://github.com/muxiaonong/Spring-Cloud/tree/master/cloudadmin Admin 简介 官方文档:What is Spring Boot Admin? SpringBootAdmin是一个用于管理和监控SpringBoot微服务的社区项目,可以使用客户端注册或者Eureka服务发现向服务端提供监控信息. 注意,服务端相当于提供UI界面,实际的监

  • Spring Boot项目抵御XSS攻击实战过程

    目录 前言 一.什么是XSS攻击 二.如何抵御XSS攻击 三.实现抵御XSS攻击 总结 前言 作为Web网站来说,抵御XSS攻击是必须要做的事情,这是非常常见的黑客攻击手段之一. 一.什么是XSS攻击 XSS意思是跨站脚本攻击,英文全称Cross Site Scripting,为了不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS. XSS攻击的手段很简单,就是通过各种手段向我们的Web网站植入JS代码.比如说普通网站的用户注册.论坛

  • 教你开发脚手架集成Spring Boot Actuator监控的详细过程

    目录 集成 引入依赖 配置文件 访问验证 端点 Endpoints Health Info 安全 高级 自定义健康检查 自定义metrics指标 PID PORT过程监控 自定义管理端点路径 自定义管理服务器端口 暴露数据给Prometheus 集成 引入依赖 在项目的pom.xml中增加以下依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-

  • Spring Boot 底层原理基础深度解析

    目录 1. 底层注解@Configuration 2. 底层注解@Import 3. 底层注解@Conditional 1. 底层注解@Configuration @Configuration 注解主要用于给容器添加组件(Bean),下面实践其用法: 项目基本结构: 两个Bean组件: User.java package com.menergy.boot.bean; /** * 用户 */ public class User { private String name; private Inte

  • Spring Boot Actuator自定义健康检查教程

    健康检查是Spring Boot Actuator中重要端点之一,可以非常容易查看应用运行至状态.本文在前文的基础上介绍如何自定义健康检查. 1. 概述 本节我们简单说明下依赖及启用配置,展示缺省健康信息.首先需要引入依赖: compile("org.springframework.boot:spring-boot-starter-actuator") 现在通过http://localhost:8080/actuator/health端点进行验证: {"status"

  • 详解Spring Boot实战之单元测试

    本文介绍使用Spring测试框架提供的MockMvc对象,对Restful API进行单元测试 Spring测试框架提供MockMvc对象,可以在不需要客户端-服务端请求的情况下进行MVC测试,完全在服务端这边就可以执行Controller的请求,跟启动了测试服务器一样. 测试开始之前需要建立测试环境,setup方法被@Before修饰.通过MockMvcBuilders工具,使用WebApplicationContext对象作为参数,创建一个MockMvc对象. MockMvc对象提供一组工具

  • Spring Boot应用监控的实战教程

    概述 Spring Boot 监控核心是 spring-boot-starter-actuator 依赖,增加依赖后, Spring Boot 会默认配置一些通用的监控,比如 jvm 监控.类加载.健康监控等. 我们之前讲过Docker容器的可视化监控,即监控容器的运行情况,包括 CPU使用率.内存占用.网络状况以及磁盘空间等等一系列信息.同样利用SpringBoot作为微服务单元的实例化技术选型时,我们不可避免的要面对的一个问题就是如何实时监控应用的运行状况数据,比如:健康度.运行指标.日志信

  • spring boot starter actuator(健康监控)配置和使用教程

    添加POM依赖: <!-- spring-boot-监控--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.bo

随机推荐