监控的本质: 收集日志后,通过分析,产生的结果

Actuator

image.png
引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-actuator</artifactId>
  4. </dependency>

image.png
image.png

在application.properties配置

  1. #以web形式暴露的端点管理包含所有(*代表所有)
  2. management.endpoints.web.exposure.include=*

image.png
在application.properties配置
①打开或关闭endpoint
management.endpoint..enabled=true/false
②info信息只需要配置文件中的属性值以“info.”开头

#例如关闭beans端点
management.endpoint.beans.enabled=false

#查看info端点的信息
info.app.name=spring-boot-demo
info.app.version=1.0

image.png
③有一个特殊的post操作命令/shutdown,可以关闭应用程序,但前提是endpoints.shutdown.enabled需要设置为true
未配置:
image.png

management.endpoint.shutdown.enabled=true

image.png
image.png④让health的细节展示

management.endpoint.health.show-details=always

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

package com.duing.health;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class CustomHealth implements HealthIndicator {

    @Override
    public Health health() {
        int errorCode=1;
        if(errorCode!=0){
            //返回不健康的指标,并且返回具体的code值
            return Health.down().withDetail("ErrorCode",errorCode).build();
        }
        //返回健康指标
        return Health.up().build();
    }

}

image.png

自定义端点

package com.duing.endpoint;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 *首先需要是一个组件
 * 然后通过@Endpoint声明是一个端点,通过id来命名
 */
@Component
@Endpoint(id = "custom")
public class StatusEndPoint {

    /**
     * 端点访问时的处理方法,通过@ReadOperation注解查找
     * 注意,需要返回json格式的数据
     * @return
     */
    @ReadOperation
    @ResponseBody
    public Map<String,String> custom(){
        Map<String,String> map=new HashMap<>();
        map.put("name","Hello custom endpoint");
        return map;
    }

}

image.png

Actuator 安全

#安全相关
#自定义端口号
management.server.port=8899
#自定义路径
management.endpoints.web.base-path=/monitor

image.png
image.png
还可以开启security功能,配置访问权限验证,这时再访问actuator功能时就会弹出登录窗口,需要输入账号密码验证后才允许访问。

引入依赖:

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

在application.properties配置账户和密码:

spring.security.user.name=klxh
spring.security.user.password=123456

image.png