实例因为出现故障、部署或自动缩放的状况,会进行持续启动、从新启动或中止操做。它可能致使它们暂时或永久不可用。为避免问题,您的负载均衡器应该从路由中跳过不健康的实例,由于它们当前没法为客户或子系统提供服务。
应用实例健康情况能够经过外部观察来肯定。您能够经过重复调用GET /health端点或经过自我报告来实现。如今主流的服务发现解决方案,会持续从实例中收集健康信息,并配置负载均衡器,将流量仅路由到健康的组件上。spring
Spring Boot-Actuator 就是帮助咱们监控咱们的Spring Boot 项目的。数据库
Spring Boot 最主要的特性就是AutoConfig(自动配置),而对于咱们这些使用者来讲也就是各类starter,
Spring Boot-Actuator 也提供了starter,为咱们自动配置,在使用上咱们只须要添加starter到咱们的依赖中,而后启动项目便可。bash
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
复制代码
经常使用Endpoint负载均衡
Spring Boot-actuator,提供了许多有用的EndPoint,对Spring Boot应用提供各类监控,下面说一下我经常使用的EndPoint:dom
/health 应用的健康状态
/configprops 获取应用的配置信息,由于Spring Boot 可能发布时是单独的Jar包,配置文件可能包含其中, 当咱们须要检查配置文件时可使用 ConfigpropsEndPoint 进行查看一些配置是否正确。
/trace 最近几回的http请求信息ide
当咱们访问 http://localhost:8088/health 时,能够看到 HealthEndPoint 给咱们提供默认的监控结果,包含 磁盘检测和数据库检测。spring-boot
{
"status": "UP",
"diskSpace": {
"status": "UP",
"total": 398458875904,
"free": 315106918400,
"threshold": 10485760
},
"db": {
"status": "UP",
"database": "MySQL",
"hello": 1
}
}
复制代码
其实看 Spring Boot-actuator 源码,你会发现 HealthEndPoint 提供的信息不只限于此,org.springframework.boot.actuate.health 包下 你会发现 ElasticsearchHealthIndicator、RedisHealthIndicator、RabbitHealthIndicator 等
也就是 HealthEndPoint 也提供 ES, Redis 等组件的健康信息。ui
自定义Indicator 扩展 HealthEndPointspa
看源码 其实 磁盘和数据库健康信息就是 DiskSpaceHealthIndicator、DataSourceHealthIndicator 来实现的,当咱们对一些咱们自定义的组件进行监控时, 咱们也能够实现个Indicator :code
@Component
public class User implements HealthIndicator {
/**
* user监控 访问: http://localhost:8088/health
*
* @return 自定义Health监控
*/
@Override
public Health health() {
return new Health.Builder().withDetail("usercount", 10) //自定义监控内容
.withDetail("userstatus", "up").up().build();
}
}
复制代码
这时咱们再次访问: http://localhost:8088/health 这时返回的结果以下,包含了咱们自定义的 User 健康信息。
{
"status": "UP",
"user": {
"status": "UP",
"usercount": 10,
"userstatus": "up"
},
"diskSpace": {
"status": "UP",
"total": 398458875904,
"free": 315097989120,
"threshold": 10485760
},
"db": {
"status": "UP",
"database": "MySQL",
"hello": 1
}
}
复制代码
其实除了扩展 HealthEndPoint 来添加一些健康检查, 咱们也能够自定定义一些EndPoint 来提供程序运行时一些信息的展现:
@Configuration
public class EndPointAutoConfig {
@Bean
public Endpoint<Map<String, Object>> customEndPoint() {
return new SystemEndPoint();
}
}
@ConfigurationProperties(prefix="endpoints.customsystem")
public class SystemEndPoint extends AbstractEndpoint<Map<String, Object>> {
public SystemEndPoint(){
super("customsystem");
}
@Override
public Map<String, Object> invoke() {
Map<String,Object> result= new HashMap<>();
Map<String, String> map = System.getenv();
result.put("username",map.get("USERNAME"));
result.put("computername",map.get("COMPUTERNAME"));
result.put("userdomain",map.get("USERDOMAIN"));
return result;
}
}
复制代码
访问 http://localhost:8088/customsystem 来查看咱们自定义的EndPoint ,返回结果以下:
{
"username": "xxx",
"userdomain": "DESKTOP-6EAN1H4",
"computername": "DESKTOP-6EAN1H4"
}复制代码