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

相關文章
相關標籤/搜索