SpringBoot 教程核心功能-Actuator 指标监控

一、 SpringBootActuator

1.1 简介

未来每一个微服务在云上部署以后,我们都需要对其进行监控、追踪、审计、控制等。SpringBoot就抽取了Actuator场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能。

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

在这里插入图片描述

1.2 springboot 2 1.x与2.x的不同

在这里插入图片描述

SpringBoot Actuator 1.x

支持SpringMVC
基于继承方式进行扩展
层级Metrics配置
自定义Metrics收集
默认较少的安全策略

SpringBoot Actuator 2.x

支持SpringMVC、JAX-RS以及Webflux
注解驱动进行扩展
层级&名称空间Metrics
底层使用MicroMeter,强大、便捷默认丰富的安全策略

1.3 如何使用

1、引入场景

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

2、访问 localhost:8080/actuator/*

3、 暴露所有监控信息为 HTTP

#management.endpoints 是所有 Actuator 的配置
#management.endpoint.端点名.xxx 对某个端点的具体配置
management:
  endpoints:
    enabled-by-default: true #暴露所有端点信息
    web:
      exposure:
        include: '*' #以 web 方式暴露所有端点
  endpoint:
    health: #health 的具体配置
      show-details: always

测试

  • http://localhost:8080/actuator/beans
  • http://localhost:8080/actuator/configprops
  • http://localhost:8080/actuator/metrics
  • http://localhost:8080/actuator/metrics/jvm.gc.pause
  • http://localhost:8080/actuator/metrics/endpointName/detailPath

4. 开启与禁用 Endpoints

1、默认所有的 Endpoints 除【shutdown 】都是开启的。

2、需要开启或禁用某个 Endpoint。配置模式为 【management.endpoint..enabled = true】

management:
  endpoints:
    enabled-by-default: false
  endpoint:
    beans:
      enabled: true
    health: 
      enabled: true

3、或者禁用所有的 Endpoint,然后手动开启指定的 Endpoint。

二、Actuator Endpoint 监控端点及开启与禁用

2.1 常使用的端点

ID描述
auditevents暴露当前应用程序的审核事件信息。需要一个AuditEventRepository组件。
beans显示应用程序中所有Spring Bean的完整列表。
caches暴露可用的缓存。
conditions显示自动配置的所有条件信息,包括匹配或不匹配的原因。
configprops显示所有@ConfigurationProperties。
env暴露Spring的属性ConfigurableEnvironment
flyway显示已应用的所有Flyway数据库迁移。 需要一个或多个Flyway组件。
health显示应用程序运行状况信息。
httptrace显示HTTP跟踪信息(默认情况下,最近100个HTTP请求-响应)。需要一个HttpTraceRepository组件。
info显示应用程序信息。
integrationgraph显示Spring integrationgraph 。需要依赖spring-integration-core。
loggers显示和修改应用程序中日志的配置。
liquibase显示已应用的所有Liquibase数据库迁移。需要一个或多个Liquibase组件。
metrics显示当前应用程序的“指标”信息。
mappings显示所有@RequestMapping路径列表。
scheduledtasks显示应用程序中的计划任务。
sessions允许从Spring Session支持的会话存储中检索和删除用户会话。需要使用Spring Session的基于Servlet的Web应用程序。
shutdown使应用程序正常关闭。默认禁用。
startup显示由ApplicationStartup收集的启动步骤数据。需要使用SpringApplication进行配置BufferingApplicationStartup。
threaddump执行线程转储。

如果您的应用程序是 Web 应用程序(SpringMVC、SpringWebFlux 或 Jersey),则可以使用以下附加端点:

ID描述
heapdump返回hprof堆转储文件。
jolokia通过HTTP暴露JMX bean(需要引入Jolokia,不适用于WebFlux)。需要引入依赖jolokia-core。
logfile返回日志文件的内容(如果已设置logging.file.name或logging.file.path属性)。支持使用HTTPRange标头来检索部分日志文件的内容。
prometheus以Prometheus服务器可以抓取的格式公开指标。需要依赖micrometer-registry-prometheus。

2.2 其中最常用的 Endpoint

  • Health:健康监控
  • Metrics:运行时指标
  • Loggers:日志记录

2.2.1 Health Endpoint

健康检查端点,我们一般用于在云平台,平台会定时的检查应用的健康情况,我们就需要 Health Endpoint 为平台返回当前应用的一系列组件监控状况的集合。

重要的几点:

  • Health Endpoint 返回的结果,应该是一系列监控检查后的一个汇总报告
  • 很多的健康检查已经自动配置好了,比如:数据库、redis 等
  • 可以很容易的添加自定义的健康检查机制
    在这里插入图片描述

2.2.2 Metrics Endpoint

提供详细的、层级的、空间指标信息,这些信息可以被 pull(主动推送)或push(被动获取)方式得到。

  • 通过 Metrics 对接多种监控系统
  • 简化核心 Metrics 开发
  • 添加自动以 Metrics 或者扩展已有 Metrics。

在这里插入图片描述

2.3 开启与禁用 Endpoints

1、默认所有的 Endpoints 除【shutdown 】都是开启的。

2、需要开启或禁用某个 Endpoint。配置模式为 【management.endpoint..enabled = true】

management:
  endpoints:
    enabled-by-default: false
  endpoint:
    beans:
      enabled: true
    health: 
      enabled: true

3、或者禁用所有的 Endpoint,然后手动开启指定的 Endpoint。

3.定制 Endpoint

3.1 定制 Health 信息

@Component
public class MyHealthIndicator extends AbstractHealthIndicator {
 
    /**
     * 真实的检查方法
     */
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        Map<String,Object> map = new HashMap<>();
 
        if (true) {
            builder.status(Status.UP);//监控
            map.put("count",1);
            map.put("ms",100);
        } else {
            builder.status(Status.DOWN);//不健康
            map.put("err","连接超时");
            map.put("ms",3000);
        }
        builder.withDetail("hello","world");
        builder.withDetails(map);
    }
}

在这里插入图片描述

3.2 定制 info 信息

方式一
编写配置文件(前提 可以访问 info Endpoint),然后可以访问 http://localhost:8080/actuator/info 来进行查看

info:
  appName: boot-admin
  appNo: 1.0.0
  mavenProjectName: @project.artifactId@ #获取 pom 文件 artifactId 属性内容
  mavenProjectVersion: @project.version@ #获取 pom 文件 version 内容

在这里插入图片描述
方式二
编写 InfoContributor

@Component
public class ExampleInfoContributor implements InfoContributor {
    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("msg", "你好")
                .withDetail("hello","world")
                .withDetails(Collections.singletonMap("key","value"));
    }
}

在这里插入图片描述

3.3 定制 Metrics 信息

3.3.1 SpringBoot 支持自动适配的 Metrics

  • 1、jvm metrics ,报告资源利用率:

各种内存和缓存池
有关垃圾收集的统计
线程利用率
加载/卸载的类数

  • 2、CPU metrics

  • 3、文件描述符 metrics

  • 4、Kafka 消费者和生产者 metrics

  • 5、Log4j2 metrics :记录每个级别记录到 Log4j2 的事件数

  • 6、Logback metrics:记录每个级别记录到 Logback 的事件数

  • 7、正常运行期间 metrics:报告正常运行时间的指标和表示应用程序绝对启动时间的固定指标

  • 8、Tomcat metrics :server.Tomcat.mbeanregistry.enabled必须设置为true才能注册所有 Tomcat metrics。

  • 9、Spring 集成 metrics。

3.3.2 增加定制 metrics

方式一

  • 可以在我们 Service 的实现类里面增加某些定制的参数,例如我们之前使用到的 AccountServiceImpl 。

  • 构造器函数传入 MeterRegistry 类型对象,用于获取定制的 Metrics 的对象
    在调用需要统计的函数时,调用对象的 相关方法。

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
    Counter counter;
 
    public AccountServiceImpl(MeterRegistry meterRegistry) {
        super();
        counter = meterRegistry.counter("AccountService.getById.count");//获取技术对象
    }
 
    @Override
    public Account getById(Serializable id) {
        counter.increment(); //每次调用就+1
        return this.baseMapper.selectById(id);
    }
}

在这里插入图片描述
每次调用 getById 方法后,下图的 value 都会增加1

在这里插入图片描述
方式二

@Configuration
public class CustomMetricsConfig {
    @Bean
    MeterBinder queueSize(Queue queue){
        return registry-> Gauge.builder("queueSize", queue::size).register(registry);
    }
 
    @Bean
    MeterRegistryCustomizer<MeterRegistry> configurer(@Value("${info.appName}") String appName) {
        return registry -> registry.config().commonTags("appName", appName);
    }
}

3.4 定制 Endpoint

@Component
@Endpoint(id = "myEndpoint")
public class MyEndpoint {
    @ReadOperation
    public Map getDockerInfo() {
        //端点的读操作
        return Collections.singletonMap("dockerInfo","docker started ...");
    }
 
    @WriteOperation
    public void stopDocker() {
        System.out.println("docker stopped");
    }
}
  • 开发 ReadinessEndpoint 来管理程序是否就绪。
  • 开发 LivenessEndpoint 来管理程序是否存活。

4.可视化

官方指南:Spring Boot Admin Reference Guide

4.1 新建一个SpringBoot 工程,作为可视化服务端

POM 依赖

        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

启动类

@EnableAdminServer
@SpringBootApplication
public class Boot05AdminserverApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(Boot05AdminserverApplication.class, args);
    }
 
}

application.yml 配置文件

server:
    port: 8888

4.2 在应用程序中建立客户端

POM 依赖

        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.3.1</version>
        </dependency>
        <!--应用中配置了 SecurityPermitAllConfig  时需要导入此依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

application.yml

spring:
  boot:
    admin:
      client:
        url: http://localhost:8888
        instance:
          prefer-ip: true #使用 IP 地址注册进来
 
management:
  endpoints:
    enabled-by-default: true #暴露所有端点信息
    web:
      exposure:
        include: '*' #以 web 方式暴露所有端点

当 pom 文件引用 spring-boot-starter-security 依赖时,需要此类

/**
 * 当 pom 文件引用 spring-boot-starter-security 依赖时,需要此类
 */
@Configuration
public class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll()
                .and().csrf().disable();
    }
}

4.3 界面

4.3 界面

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个开发框架,它提供了一系列核心功能来简化Java应用程序的开发和部署。以下是Spring Boot的一些核心功能: 1. 自动配置(Auto-configuration):Spring Boot根据应用程序的依赖和配置自动进行配置,减少了繁琐的手动配置过程。 2. 起步依赖(Starter dependencies):Spring Boot提供了一系列预定义的依赖库,你可以通过简单地添加这些依赖来快速搭建应用程序,并且不需要关心依赖库之间的版本兼容性。 3. 嵌入式容器(Embedded container):Spring Boot集成了多个嵌入式容器,例如Tomcat、Jetty和Undertow,使得应用程序可以直接以可执行的JAR包形式运行,不需要额外安装和配置外部容器。 4. 简化的配置(Simplified configuration):Spring Boot采用约定优于配置的原则,通过提供统一的配置文件格式(如application.properties或application.yml)来简化配置工作。 5. 健康检查(Health check):Spring Boot提供了健康检查功能,可以通过HTTP端点来监控应用程序的状态和健康情况。 6. 监控和管理(Monitoring and management):Spring Boot集成了Actuator模块,提供了丰富的监控和管理功能,如查看应用程序的运行指标、管理应用程序的配置等。 7. 强大的开发工具支持(Powerful development tools support):Spring Boot提供了很多开发工具支持,如自动重启、热部署、自动测试等,提高了开发效率。 这些是Spring Boot的一些核心功能,它们使得Java应用程序的开发和部署变得更加简单和高效。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值