spring-boot-actuator学习总结和思考

一. 什么是Actuator

      actuator是从spring-boot中带的一套用来进行系统健康检查的一个模块,具有即插即用的能力。它提供了一套基于restful的api接口,可以帮助我们方便的通过相应的接口了解到系统资源占用、beans、dump、mappings等相关的信息。同时其还具有能力,可以基于HealthIndicators实现自定义的安全与健康检查。

     actuator目前自带的接口如下:

ID
描述
Sensitive Default

actuator

Provides a hypermedia-based “discovery page” for the other endpoints. Requires Spring HATEOAS to be on the classpath.

true

auditevents

Exposes audit events information for the current application.

true

autoconfig

Displays an auto-configuration report showing all auto-configuration candidates and the reason why they ‘were’ or ‘were not’ applied.

告诉你为什么会有这个Bean,或者为什么没有这个Bean。提供了报告,列出了计算过的所有条件,根据条件是否通过进行分组

http://10.4.187.57:8412/autoconfig

true

beans

显示应用所有的Bean装配报告.

◆bean: Spring应用程序上下文中的Bean名称或ID。
◆resource: .class文件的物理位置,通常是一个URL,指向构建出的JAR文件。
◆dependencies:当前Bean注入的Bean ID列表。
◆scope: Bean的作用域(通常是单例,这也是默认作用域)。
◆type: Bean的Java类型。

http://10.4.187.57:8412/beans

true

configprops

显示应用所有的 @ConfigurationProperties配置信息.用来显示springboot自动配置的属性,例如:springboot的默认值等。

http://10.4.187.57:8412/configprops

true

dump

显示当前应用的所有线程dump情况。当出现内存占用过高等情况下,可以帮助分析线程的使用情况,帮助定位问题。返回数据的结构如下:

http://10.4.187.57:8412/dump

true

env

显示Spring的 ConfigurableEnvironment属性.返回数据结构如下:

 http://10.4.187.57:8412/env

true

flyway

显示任意的Flyway数据库迁移被应用情况(一般情况下该功能使用的场景很小)。.默认情况下,该功能是关闭的,访问会出现404错误。

 

true

health

显示系统的健康信息 (when the application is secure, a simple ‘status’ when accessed over an unauthenticated connection or full message details when authenticated).

返回结果  展开原码

false

info

显示任意的应用程序信息.默认是空,如果需要显示自己应用的相关信息,可以在配置文件中添加相应的节点即可。并通过接口输出,例如如下的配置:

info.app.name=ecs

info.app.version=1.0.0

  info.build.artifactId=@project.artifactId@

info.build.version=@project.version@

 

执行/info

{ app: { version: "1.0.0", name: "ecs" },
    build: { artifactId: "execute-count-server", version: "0.0.3" }
}

/info 是用来在构建的时候,自动扩展属性的。对于Maven项目,可以通过 @..@ 占位符引用Maven的’project properties’。

false

loggers

Shows and modifies the configuration of loggers in the application.

true

liquibase

Shows any Liquibase database migrations that have been applied.

true

metrics

显示当前应用的 ‘metrics’信息.即可以全量查询也可以单个指标查询,路径格式为:/metrics/{name:.*}

  • 系统内存总量(mem),单位:Kb
  • 空闲内存数量(mem.free),单位:Kb
  • 处理器数量(processors)
  • 系统正常运行时间(uptime),单位:毫秒
  • 应用上下文(就是一个应用实例)正常运行时间(instance.uptime),单位:毫秒
  • 系统平均负载(systemload.average)
  • 堆信息(heap,heap.committed,heap.init,heap.used),单位:Kb
  • 线程信息(threads,thread.peak,thead.daemon)
  • 类加载信息(classes,classes.loaded,classes.unloaded)
  • 垃圾收集信息(gc.xxx.count, gc.xxx.time)
  • 最大连接数(datasource.xxx.max)
  • 最小连接数(datasource.xxx.min)
  • 活动连接数(datasource.xxx.active)
  • 连接池的使用情况(datasource.xxx.usage)


http://10.4.187.57:8412/metrics

true

mappings

显示系统所有的 @RequestMapping 路径.

http://10.4.187.57:8412/mappings

true

shutdown

Allows the application to be gracefully shutdown (not enabled by default).

true

trace

显示trace信息 (默认显示最后100个HTTP请求).

http://10.4.187.57:8412/trace

tru


二. actuator的个性化配置

1.修改端点Id 

每个Actuator端点都是有一个特定的ID用来决定端点的路径。/beans端点的默认ID就是 beans 。端点的路径是由ID决定的, 那么可以通过修改ID来改变端点的路径。 要做的就是设置一个属性,属性名是  endpoints.endpoint-id.id 。
如把/beans改为/beansome:
endpoints.beans.id=beansome
这时要是想查看bean的信息时,路径就由原来的/beans变为/beansome;

2.启用和禁用端点

默认情况下,所有端点(除了/shutdown)都是启用的。
禁用端点所有的端点:
endpoints.enabled=false
禁用某个特定的端点:
endpoints.endpoint-id.enabled=false
注意奥!
禁用后,再次访问URL时,会出现404错误。

3.添加自定义度量信息

3.1 简单的自定义度量信息:

springBoot自动配置Actuator创建CounterService的实例,并将其注册为Spring的应用程序上下文中的Bean。

CounterService这个接口里定义了三个方法分别用来增加、减少或重置特定名称的度量值。

代码如下:

package org.springframework.boot.actuate.metrics;

public interface CounterService {

  void increment(String metricName);

  void decrement(String metricName);

  void reset(String metricName);

}

Actuator的自动配置还会配置一个GaugeService类型的Bean。

代码如下:

package org.springframework.boot.actuate.metrics;

public interface GaugeService {

    void submit(String metricName, double value);

}

自己写的一个实例:

@Controller 
public class HelloController { 
     @Autowired   
     private CounterService counterService;  
     @Autowired  
     private GaugeService gaugeService;    
     @RequestMapping(value = "/login", method=RequestMethod.GET)   
     public String login() {
        counterService.increment("logintimes:");
        gaugeService.submit("loginLastTime:",System.currentTimeMillis());      
        return "login";   
      }
}

在运行/ metrics时,出现自定义的度量信息。

3.2 相对复杂点的自定义度量信息
 主要是写一个类实现public Metrics接口,提供自己想要的度量信息。该接口定义了一个metrics()方法,返回一个Metric对象的集合

代码如下:

@Componentpublic 
class CustomMetrics implements PublicMetrics {   
    private ApplicationContext applicationContext;
    @Autowide 
    public CustomMetrics(ApplicationContext applicationContext) {       
       this.applicationContext = applicationContext;   
    } 
    @Override  
    public Collection<Metric<?>> metrics() {    
        List<Metric<?>> metrics = new ArrayList<Metric<?>>();
        metrics.add(new Metric<Long>("spring.startup-date",applicationContext.getStartupDate()));
        metrics.add(new Metric<Integer>("spring.bean.definitions",applicationContext.getBeanDefinitionCount()));
        metrics.add(new Metric<Integer>("spring.beans",applicationContext.getBeanNamesForType(Object.class).length));
        metrics.add(new Metric<Integer>("spring.controllers",applicationContext.getBeanNamesForAnnotation(Controller.class).length));      
        return metrics;  
     }
}

运行结果中可以找到以上自定义的度量信息

"spring.startup-date":1477211367363,
"spring.bean.definitions":317,
"spring.beans":331,
"spring.controllers":3,

4.插入自定义健康指示器

      自定义健康指示器时,需要实现HealthIndicator,重写health()方法即可。调用withDetail()方法向健康记录里添加其他附加信息。有多个附加信息时,可多次调用withDetail()方法,每次设置一个健康记录的附加字段。

示例(关于一个异常的健康指示器)如下:

@Componentpublic 
class CustomHealth implements HealthIndicator{   
 @Override   
 public Health health() {   
     try {        
         RestTemplate restTemplate = new RestTemplate();   
         restTemplate.getForObject("http://localhost:8080/index",String.class);          
         return Health.up().build();      
     }catch (Exception e){      
      return Health.down().withDetail("down的原因:",e.getMessage()).build();     
      }    
  }
}

 运行“http://localhost:8080/health
之后就会出现一些列健康指示。有时候有的浏览器仅仅出现{"status":"DOWN"},为什么会是这样呢?官网给了我们答案

Shows application health information (when the application is secure, a simple ‘status’ when accessed over an unauthenticated connection or full message details when authenticated)
而且要求Sensitive Default 为flase

5. 更改健康检查端口

默认情况下健康检查端口和app端口是使用同一个,如我们之前使用的http://127.0.0.1:8080/health,但是为了安全起见、不影响业务我们最好使用另外的端口进行健康检查,如使用9090端口,在application.properties文件中设置management.port=9090

6.跨域访问的支持

默认情况下是不支持对actuator端点的跨域访问,假如我们在一个统一的监控平台下希望支持跨域调用这些端点来指向相应的操作,则需要作如下的配置。

 

Cross-origin resource sharing (CORS) is a W3C specification that allows you to specify in a flexible way what kind of cross domain requests are authorized. Actuator’s MVC endpoints can be configured to support such scenarios.

 

CORS support is disabled by default and is only enabled once the endpoints.cors.allowed-origins property has been set. The configuration below permitsGET and POST calls from the example.com domain:

 

endpoints.cors.allowed-origins=http://example.com
endpoints.cors.allowed-methods=GET,POST

 

 

Check EndpointCorsProperties for a complete list of options.

 

7.已经进行自动配置的HealthIndicators

The following HealthIndicators are auto-configured by Spring Boot when appropriate:

 

Name
Description

CassandraHealthIndicator

Checks that a Cassandra database is up.

DiskSpaceHealthIndicator

Checks for low disk space.

DataSourceHealthIndicator

Checks that a connection to DataSource can be obtained.

ElasticsearchHealthIndicator

Checks that an Elasticsearch cluster is up.

JmsHealthIndicator

Checks that a JMS broker is up.

MailHealthIndicator

Checks that a mail server is up.

MongoHealthIndicator

Checks that a Mongo database is up.

RabbitHealthIndicator

Checks that a Rabbit server is up.

RedisHealthIndicator

Checks that a Redis server is up.

SolrHealthIndicator

Checks that a Solr server is up.

 

 

It is possible to disable them all using the management.health.defaults.enabled property.

 

8.通过Remote-Shell来进行监控和管理

Spring Boot supports an integrated Java shell called ‘CRaSH’. You can use CRaSH to ssh or telnet into your running application. To enable remote shell support, add the following dependency to your project:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-remote-shell</artifactId>
 </dependency>

 

The remote shell is deprecated and will be removed in Spring Boot 2.0.

 

 

If you want to also enable telnet access you will additionally need a dependency on org.crsh:crsh.shell.telnet.

 

 

CRaSH requires to run with a JDK as it compiles commands on the fly. If a basic help command fails, you are probably running with a JRE.

 

三. 项目应用现状和思考

        目前只有hotel.pms.admin该服务应用到了该框架,只是针对不同的环境做了启用和不启用的相关配置,并没有做太多针对项目实际情况的应用。例如:

         1.所有的启动检测接口可以使用健康检查是否有效的判断,访问http://host:port/health的地址,并在所有项目内铺开。

         2.针对所有应用的监控,都可以添加autuator的相关配置,方便在线上出现和资源消耗相关的问题时,可以对问题进行初步的排查,并了解系统资源相关的第一手信息。

         3.通过bean相关的分析,可以对无效的相关包引用进行排除。毕竟多加载一个包也是对资源的一个浪费。

         4.通过info信息来显示服务端应用的最新信息以了解发布的最新版本。

 

四.总结

        建议在Q2开始推动在所有的后端服务内推广嵌入actuator相关的配置,以保障服务基础配置的标准化。

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
spring-boot-starter-actuatorSpring Boot框架中的一个模块,它提供了一系列用于监控和管理应用程序的端点(endpoints),比如/health、/info、/metrics等。这些端点可以通过HTTP请求访问,返回应用程序的各种指标和状态信息。 spring-boot-starter-actuator的原理主要包括以下几个方面: 1. 自动配置:Spring Boot框架提供了自动配置功能,可以根据应用程序的依赖项和配置文件来自动配置spring-boot-starter-actuator模块。 2. 端点映射:spring-boot-starter-actuator使用Spring MVC框架来处理HTTP请求。它通过端点映射(Endpoint Mapping)将HTTP请求映射到相应的端点处理器(Endpoint Handler)上。 3. 端点处理器:每个端点都有一个对应的处理器,用于处理HTTP请求并返回响应。端点处理器可以是自定义的Java类,也可以是Spring Boot框架提供的默认实现。 4. 数据源:spring-boot-starter-actuator会从应用程序的各种数据源中收集指标和状态信息,比如JVM内存使用情况、数据库连接池状态等。这些数据源可以是应用程序本身、第三方库、操作系统等。 5. 安全性:为了保护应用程序的安全性,spring-boot-starter-actuator提供了一些安全功能,比如基于角色的访问控制、IP地址过滤等。可以通过配置文件来配置这些安全功能。 总之,spring-boot-starter-actuator通过自动配置、端点映射、端点处理器、数据源和安全性等机制,实现了对应用程序的监控和管理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值