Spring Boot Actuator 学习手札

官方文档地址:https://docs.spring.io/spring...html

关于Endpoints

Actuator endpoints 提供对程序监控及互动的相关功能,Spring Boot内置了一些endpoints,用户也能够根据须要建立自定义的endpoints。web

内置的endpoints:
auditevents、beans、caches、conditions、configprops、env、flyway、health、httptrace、info、integrationgraph、loggers、liquibase、metrics、mappings、scheduledtasks、sessions、shutdown、threaddumpspring

health endpoint默认映射到/actuator/health。浏览器

启用endpointssession

management.endpoint.shutdown.enabled=true

关闭全部默认endpoint,单独打开infoapp

management.endpoints.enabled-by-default=false
management.endpoint.info.enabled=true

对外暴露endpoints,分为JMX和HTTP(web)
include包含
exclude排除spring-boot

management.endpoints.jmx.exposure.exclude
management.endpoints.jmx.exposure.include
management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.include

jmx方式打开health infoui

management.endpoints.jmx.exposure.include=health,info

web排除env beans,其他打开翻译

management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans

示例1

pom添加依赖code

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

打开浏览器,输入

http://localhost:8080/actuator/

页面返回

{"\_links":{"self":{"href":"http://localhost:8080/actuator","templated":false},"health":{"href":"http://localhost:8080/actuator/health","templated":false},"health-path":{"href":"http://localhost:8080/actuator/health/{\*path}","templated":true},"info":{"href":"http://localhost:8080/actuator/info","templated":false}}}

若要关闭其中的endpoint,例如health,可在application.properties添加

management.endpoint.health.enabled=false

实现自定义endpoint

一个类加上@Bean @Endpoint标签,类里面的任何方法加上@ReadOperation/@WriteOperation/@DeleteOperation,都会经过JMX和HTTP对外暴露。
(
@ReadOperation对应HTTP GET
@WriteOperation对应HTTP POST
@DeleteOperation对应HTTP DELETE
)

上面是官方文档的说明,我作了个渣翻译。实际上,光打上@Component @Endpoint两个标签,自定义的Endpoint并不会对外暴露,须要在配置里指定id,才会生效。

示例2

package solo.zsh.actuator.p1;

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

@Component
@Endpoint(id = "p1")
public class Endpoint1 {

    @ReadOperation
    public String func1() {
        return "my custom endpoint";
    }
}

application.properties里添加:

management.endpoints.web.exposure.include=p1

浏览器输入 http://localhost:8080/actuator/p1,页面返回my custom endpoint

相关文章
相关标签/搜索