spring boot actuator專題


Spring Boot Actuator / Swagger

 

I'm working on Spring Boot application and i use Swagger for the documentation.

I have adding Spring Boot Actuator on my application, but now i want to add the new services creating by actuator (/health /metrics ..) on my swagger documentation.

I don't find how configure Actuator and Swagger.

You can configure in Swagger which paths you wanted added to the documentation.

 

@Bean
public Docket appApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
                     ....

}

Will display all available endpoints.

.paths(PathSelectors.ant("/mypath/**"))

will limit only to endpoints exposed in mypath.

 https://stackoverflow.com/questions/33673283/spring-boot-actuator-swagger

 


spring-boot-starter-actuator模塊的實現對於實施微服務的中小團隊來說,
可以有效地減少監控系統在采集應用指標時的開發量。
當然,它也並不是萬能的,有時候我們也需要對其做一些簡單的擴展來幫助我們實現自身系統個性化的監控需求。
下面,在本文中,我們將詳解的介紹一些關於spring-boot-starter-actuator模塊的內容,包括它的原生提供的端點以及一些常用的擴展和配置方式。

/autoconfig:該端點用來獲取應用的自動化配置報告,其中包括所有自動化配置的候選項。
同時還列出了每個候選項自動化配置的各個先決條件是否滿足。
所以,該端點可以幫助我們方便的找到一些自動化配置為什么沒有生效的具體原因。
該報告內容將自動化配置內容分為兩部分:

positiveMatches中返回的是條件匹配成功的自動化配置
negativeMatches中返回的是條件匹配不成功的自動化配置

{
    "positiveMatches": { // 條件匹配成功的
        "EndpointWebMvcAutoConfiguration": [
            {
                "condition": "OnClassCondition",
                "message": "@ConditionalOnClass classes found: 
javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet" }, { "condition": "OnWebApplicationCondition", "message": "found web application StandardServletEnvironment" } ], ... }, "negativeMatches": { // 條件不匹配成功的 "HealthIndicatorAutoConfiguration.DataSourcesHealthIndicatorConfiguration": [ { "condition": "OnClassCondition", "message": "required @ConditionalOnClass classes not found: org.springframework.jdbc.core.JdbcTemplate" } ], ... } }

從如上示例中我們可以看到,每個自動化配置候選項中都有一系列的條件,
比如上面沒有成功匹配的HealthIndicatorAutoConfiguration.DataSourcesHealthIndicatorConfiguration配置,
它的先決條件就是需要在工程中包含org.springframework.jdbc.core.JdbcTemplate類,
由於我們沒有引入相關的依賴,它就不會執行自動化配置內容。
所以,當我們發現有一些期望的配置沒有生效時,就可以通過該端點來查看沒有生效的具體原因。

 

/configprops:該端點用來獲取應用中配置的屬性信息報告。
從下面該端點返回示例的片段中,
我們看到返回了關於該短信的配置信息,
prefix屬性代表了屬性的配置前綴,
properties代表了各個屬性的名稱和值。
所以,我們可以通過該報告來看到各個屬性的配置路徑,
比如我們要關閉該端點,就可以通過使用endpoints.configprops.enabled=false來完成設置。

{
    "configurationPropertiesReportEndpoint": {
        "prefix": "endpoints.configprops",
        "properties": {
            "id": "configprops",
            "sensitive": true,
            "enabled": true
        }
    },
    ...
}

/env:該端點與/configprops不同,它用來獲取應用所有可用的環境屬性報告。
包括:環境變量、JVM屬性、應用的配置配置、命令行中的參數。
從下面該端點返回的示例片段中,
我們可以看到它不僅返回了應用的配置屬性,還返回了系統屬性、環境變量等豐富的配置信息,
其中也包括了應用還沒有沒有使用的配置。
所以它可以幫助我們方便地看到當前應用可以加載的配置信息,
並配合@ConfigurationProperties注解將它們引入到我們的應用程序中來進行使用。
另外,為了配置屬性的安全,對於一些類似密碼等敏感信息,該端點都會進行隱私保護,
但是我們需要讓屬性名中包含:password、secret、key這些關鍵詞,
這樣該端點在返回它們的時候會使用*來替代實際的屬性值。

 

/mappings:該端點用來返回所有Spring MVC的控制器映射關系報告。
從下面的示例片段中,我們可以看該報告的信息與我們在啟用Spring MVC的Web應用時輸出的日志信息類似,
其中
bean屬性標識了該映射關系的請求處理器,
method屬性標識了該映射關系的具體處理類和處理函數。

{
    "/webjars/**": {
        "bean": "resourceHandlerMapping"
    },
    "/**": {
        "bean": "resourceHandlerMapping"
    },
    "/**/favicon.ico": {
        "bean": "faviconHandlerMapping"
    },
    "{[/hello]}": {
        "bean": "requestMappingHandlerMapping",
        "method": "public java.lang.String com.didispace.web.HelloController.index()"
    },
    "{[/mappings || /mappings.json],methods=[GET],produces=[application/json]}": {
        "bean": "endpointHandlerMapping",
        "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"
    },
    ...
}


/info:該端點用來返回一些應用自定義的信息。
默認情況下,該端點只會返回一個空的json內容。
我們可以在application.properties配置文件中通過info前綴來設置一些屬性,比如下面這樣:
info.app.name=spring-boot-hello
info.app.version=v1.0.0
再訪問/info端點,我們可以得到下面的返回報告,其中就包含了上面我們在應用自定義的兩個參數。

{
    "app": {
        "name": "spring-boot-hello",
        "version": "v1.0.0"
    }
}

 

度量指標類
上面我們所介紹的應用配置類端點所提供的信息報告在應用啟動的時候都已經基本確定了其返回內容,
可以說是一個靜態報告。而度量指標類端點提供的報告內容則是動態變化的,
這些端點提供了應用程序在運行過程中的一些快照信息,
比如:內存使用情況、HTTP請求統計、外部資源指標等。
這些端點對於我們構建微服務架構中的監控系統非常有幫助,
由於Spring Boot應用自身實現了這些端點,所以我們可以很方便地利用它們來收集我們想要的信息,
以制定出各種自動化策略。下面,我們就來分別看看這些強大的端點功能。

/metrics:該端點用來返回當前應用的各類重要度量指標,比如:內存信息、線程信息、垃圾回收信息等。

{
  "mem": 541305,
  "mem.free": 317864,
  "processors": 8,
  "instance.uptime": 33376471,
  "uptime": 33385352,
  "systemload.average": -1,
  "heap.committed": 476672,
  "heap.init": 262144,
  "heap.used": 158807,
  "heap": 3701248,
  "nonheap.committed": 65856,
  "nonheap.init": 2496,
  "nonheap.used": 64633,
  "nonheap": 0,
  "threads.peak": 22,
  "threads.daemon": 20,
  "threads.totalStarted": 26,
  "threads": 22,
  "classes": 7669,
  "classes.loaded": 7669,
  "classes.unloaded": 0,
  "gc.ps_scavenge.count": 7,
  "gc.ps_scavenge.time": 118,
  "gc.ps_marksweep.count": 2,
  "gc.ps_marksweep.time": 234,
  "httpsessions.max": -1,
  "httpsessions.active": 0,
  "gauge.response.beans": 55,
  "gauge.response.env": 10,
  "gauge.response.hello": 5,
  "gauge.response.metrics": 4,
  "gauge.response.configprops": 153,
  "gauge.response.star-star": 5,
  "counter.status.200.beans": 1,
  "counter.status.200.metrics": 3,
  "counter.status.200.configprops": 1,
  "counter.status.404.star-star": 2,
  "counter.status.200.hello": 11,
  "counter.status.200.env": 1
}

從上面的示例中,我們看到有這些重要的度量值:

系統信息:包括處理器數量processors、運行時間uptime和instance.uptime、系統平均負載systemload.average。
mem.*:內存概要信息,包括分配給應用的總內存數量以及當前空閑的內存數量。這些信息來自java.lang.Runtime。
heap.*:堆內存使用情況。這些信息來自java.lang.management.MemoryMXBean接口中getHeapMemoryUsage方法獲取的java.lang.management.MemoryUsage。
nonheap.*:非堆內存使用情況。這些信息來自java.lang.management.MemoryMXBean接口中getNonHeapMemoryUsage方法獲取的java.lang.management.MemoryUsage。
threads.*:線程使用情況,包括線程數、守護線程數(daemon)、線程峰值(peak)等,這些數據均來自java.lang.management.ThreadMXBean。
classes.*:應用加載和卸載的類統計。這些數據均來自java.lang.management.ClassLoadingMXBean。
gc.*:垃圾收集器的詳細信息,包括垃圾回收次數gc.ps_scavenge.count、垃圾回收消耗時間gc.ps_scavenge.time、標記-清除算法的次數gc.ps_marksweep.count、標記-清除算法的消耗時間gc.ps_marksweep.time。這些數據均來自java.lang.management.GarbageCollectorMXBean。
httpsessions.*:Tomcat容器的會話使用情況。包括最大會話數httpsessions.max和活躍會話數httpsessions.active。該度量指標信息僅在引入了嵌入式Tomcat作為應用容器的時候才會提供。
gauge.*:HTTP請求的性能指標之一,它主要用來反映一個絕對數值。比如上面示例中的gauge.response.hello: 5,它表示上一次hello請求的延遲時間為5毫秒。
counter.*:HTTP請求的性能指標之一,它主要作為計數器來使用,記錄了增加量和減少量。
如上示例中counter.status.200.hello: 11,它代表了hello請求返回200狀態的次數為11。

對於gauge.*和counter.*的統計,這里有一個特殊的內容請求star-star,它代表了對靜態資源的訪問。
這兩類度量指標非常有用,我們不僅可以使用它默認的統計指標,還可以在程序中輕松的增加自定義統計值。
只需要通過注入org.springframework.boot.actuate.metrics.CounterService和org.springframework.boot.actuate.metrics.GaugeService來實現自定義的統計指標信息。
比如:我們可以像下面這樣自定義實現對hello接口的訪問次數統計。

@RestController
public class HelloController {

    @Autowired
    private CounterService counterService;

    @RequestMapping("/hello")
    public String greet() {
        counterService.increment("didispace.hello.count");
        return "";
    }

}


/metrics端點可以提供應用運行狀態的完整度量指標報告,這項功能非常的實用,
但是對於監控系統中的各項監控功能,它們的監控內容、數據收集頻率都有所不同,
如果我們每次都通過全量獲取報告的方式來收集,略顯粗暴。
所以,我們還可以通過/metrics/{name}接口來更細粒度的獲取度量信息,
比如我們可以通過訪問/metrics/mem.free來獲取當前可用內存數量。

/health:該端點在一開始的示例中我們已經使用過了,它用來獲取應用的各類健康指標信息。
在spring-boot-starter-actuator模塊中自帶實現了一些常用資源的健康指標檢測器。
這些檢測器都通過HealthIndicator接口實現,並且會根據依賴關系的引入實現自動化裝配,
比如用於檢測磁盤的DiskSpaceHealthIndicator、檢測DataSource連接是否可用的DataSourceHealthIndicator等。
有時候,我們可能還會用到一些Spring Boot的Starter POMs中還沒有封裝的產品來進行開發,
比如:當使用RocketMQ作為消息代理時,由於沒有自動化配置的檢測器,
所以我們需要自己來實現一個用來采集健康信息的檢測器。
比如,我們可以在Spring Boot的應用中,
為org.springframework.boot.actuate.health.HealthIndicator接口實現一個對RocketMQ的檢測器類:

@Component
public class RocketMQHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        int errorCode = check();
        if (errorCode != 0) {
          return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

      private int check() {
         // 對監控對象的檢測操作
      }
}

通過重寫health()函數來實現健康檢查,返回的Heath對象中,共有兩項內容,一個是狀態信息,
除了該示例中的UP與DOWN之外,還有UNKNOWN和OUT_OF_SERVICE,可以根據需要來實現返回;
還有一個詳細信息,采用Map的方式存儲,在這里通過withDetail函數,注入了一個Error Code信息,我們也可以填入一下其他信息,
比如,檢測對象的IP地址、端口等。
重新啟動應用,並訪問/health接口,我們在返回的JSON字符串中,將會包含了如下信息:

"rocketMQ": {
  "status": "UP"
}

/dump:該端點用來暴露程序運行中的線程信息。
它使用java.lang.management.ThreadMXBean的dumpAllThreads方法來返回所有含有同步信息的活動線程詳情。

/trace:該端點用來返回基本的HTTP跟蹤信息。
默認情況下,跟蹤信息的存儲采用org.springframework.boot.actuate.trace.InMemoryTraceRepository實現的內存方式,始終保留最近的100條請求記錄。
它記錄的內容格式如下:

[
    {
        "timestamp": 1482570022463,
        "info": {
            "method": "GET",
            "path": "/metrics/mem",
            "headers": {
                "request": {
                    "host": "localhost:8881",
                    "connection": "keep-alive",
                    "cache-control": "no-cache",
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) 
                                    Chrome/53.0.2785.143 Safari/537.36",
                    "postman-token": "9817ea4d-ad9d-b2fc-7685-9dff1a1bc193",
                    "accept": "*/*",
                    "accept-encoding": "gzip, deflate, sdch",
                    "accept-language": "zh-CN,zh;q=0.8"
                },
                "response": {
                    "X-Application-Context": "hello:dev:8881",
                    "Content-Type": "application/json;charset=UTF-8",
                    "Transfer-Encoding": "chunked",
                    "Date": "Sat, 24 Dec 2016 09:00:22 GMT",
                    "status": "200"
                }
            }
        }
    },
    ...
]


操作控制類
仔細的讀者可能會發現,我們在“初識Actuator”時運行示例的控制台中輸出的所有監控端點,
已經在介紹應用配置類端點和度量指標類端點時都講解完了。
那么還有哪些是操作控制類端點呢?
實際上,由於之前介紹的所有端點都是用來反映應用自身的屬性或是運行中的狀態,
相對於操作控制類端點沒有那么敏感,所以他們默認都是啟用的。
而操作控制類端點擁有更強大的控制能力,如果要使用它們的話,需要通過屬性來配置開啟。

在原生端點中,只提供了一個用來關閉應用的端點:/shutdown。我們可以通過如下配置開啟它:

endpoints.shutdown.enabled=true
在配置了上述屬性之后,只需要訪問該應用的/shutdown端點就能實現關閉該應用的遠程操作。
由於開放關閉應用的操作本身是一件非常危險的事,
所以真正在線上使用的時候,我們需要對其加入一定的保護機制,
比如:
定制Actuator的端點路徑、整合Spring Security進行安全校驗等。

http://www.open-open.com/lib/view/open1486282830132.html


SpringBoot 是為了簡化 Spring 應用的創建、運行、調試、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規范,引入相關的依賴就可以輕易的搭建出一個 WEB 工程

actuatorspring boot項目中非常強大一個功能,有助於對應用程序進行監視和管理,通過 restful api 請求來監管、審計、收集應用的運行情況,針對微服務而言它是必不可少的一個環節…

Endpoints


actuator 的核心部分,它用來監視應用程序及交互,spring-boot-actuator中已經內置了非常多的 Endpoints(health、info、beans、httptrace、shutdown等等),同時也允許我們自己擴展自己的端點

Spring Boot 2.0 中的端點和之前的版本有較大不同,使用時需注意。另外端點的監控機制也有很大不同,啟用了不代表可以直接訪問,還需要將其暴露出來,傳統的management.security管理已被標記為不推薦。

內置Endpoints
id desc Sensitive
auditevents 顯示當前應用程序的審計事件信息 Yes
beans 顯示應用Spring Beans的完整列表 Yes
caches 顯示可用緩存信息 Yes
conditions 顯示自動裝配類的狀態及及應用信息 Yes
configprops 顯示所有 @ConfigurationProperties 列表 Yes
env 顯示 ConfigurableEnvironment 中的屬性 Yes
flyway 顯示 Flyway 數據庫遷移信息 Yes
health 顯示應用的健康信息(未認證只顯示status,認證顯示全部信息詳情) No
info 顯示任意的應用信息(在資源文件寫info.xxx即可) No
liquibase 展示Liquibase 數據庫遷移 Yes
metrics 展示當前應用的 metrics 信息 Yes
mappings 顯示所有 @RequestMapping 路徑集列表 Yes
scheduledtasks 顯示應用程序中的計划任務 Yes
sessions 允許從Spring會話支持的會話存儲中檢索和刪除用戶會話。 Yes
shutdown 允許應用以優雅的方式關閉(默認情況下不啟用) Yes
threaddump 執行一個線程dump Yes
httptrace 顯示HTTP跟蹤信息(默認顯示最后100個HTTP請求 - 響應交換) Yes

導入依賴


在 pom.xml 中添加 spring-boot-starter-actuator 的依賴

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

注意事項

如果要訪問info接口想獲取maven中的屬性內容請記得添加如下內容

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>build-info</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

 

屬性配置


在 application.properties 文件中配置actuator的相關配置,其中info開頭的屬性,就是訪問info端點中顯示的相關內容,值得注意的是Spring Boot2.x中,默認只開放了info、health兩個端點,剩余的需要自己通過配置management.endpoints.web.exposure.include屬性來加載(有include自然就有exclude,不做詳細概述了)。如果想單獨操作某個端點可以使用management.endpoint.端點.enabled屬性進行啟用或禁用

# 描述信息 info.blog-url=https://blog.csdn.net/liupeifeng3514 info.author=WaKengMaiNi info.version=@project.version@ # 加載所有的端點/默認只加載了 info / health management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always # 可以關閉指定的端點 management.endpoint.shutdown.enabled=false # 路徑映射,將 health 路徑映射成 rest_health 那么在訪問 health 路徑將為404,因為原路徑已經變成 rest_health 了,一般情況下不建議使用 # management.endpoints.web.path-mapping.health=rest_health

簡單測試

啟動項目,訪問 http://localhost:8080/actuator/info 看到如下內容代表配置成功

{
  "blog-url": "https://blog.csdn.net/liupeifeng3514", "author": "WaKengMaiNi", "version": "0.0.1-SNAPSHOT" }

自定義 - 重點


上面講了很多都是配置相關,以及自帶的一些端點,在實際應用中有時候默認並不能滿足我們的要求,比如Spring Boot默認的健康端點就很有可能不能滿足

默認裝配 HealthIndicators

下列是依賴spring-boot-xxx-starter后相關HealthIndicator的實現(通過management.health.defaults.enabled 屬性可以禁用它們),但想要獲取一些額外的信息時,自定義的作用就體現出來了…

名稱 描述
CassandraHealthIndicator 檢查 Cassandra 數據庫是否啟動。
DiskSpaceHealthIndicator 檢查磁盤空間不足。
DataSourceHealthIndicator 檢查是否可以獲得連接 DataSource。
ElasticsearchHealthIndicator 檢查 Elasticsearch 集群是否啟動。
InfluxDbHealthIndicator 檢查 InfluxDB 服務器是否啟動。
JmsHealthIndicator 檢查 JMS 代理是否啟動。
MailHealthIndicator 檢查郵件服務器是否啟動。
MongoHealthIndicator 檢查 Mongo 數據庫是否啟動。
Neo4jHealthIndicator 檢查 Neo4j 服務器是否啟動。
RabbitHealthIndicator 檢查 Rabbit 服務器是否啟動。
RedisHealthIndicator 檢查 Redis 服務器是否啟動。
SolrHealthIndicator 檢查 Solr 服務器是否已啟動。
健康端點(第一種方式)

實現HealthIndicator接口,根據自己的需要判斷返回的狀態是UP還是DOWN,功能簡單。

package com.lpf.chapter13.health;

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

/**
 * <p>自定義健康端點</p>
 */
@Component("my1")
public class MyHealthIndicator implements HealthIndicator {

    private static final String VERSION = "v1.0.0";

    @Override
    public Health health() {
        int code = check();
        if (code != 0) {
            Health.down().withDetail("code", code).withDetail("version", VERSION).build();
        }
        return Health.up().withDetail("code", code)
                .withDetail("version", VERSION).up().build();
    }

    private int check() {

        return 0;
    }
}
 

簡單測試

啟動項目,訪問 http://localhost:8080/actuator/health 看到如下內容代表配置成功

{
  "status": "UP", "details": { "my1": { "status": "UP", "details": { "code": 0, "version": "v1.0.0" } }, "diskSpace": { "status": "UP", "details": { "total": 112090574848, "free": 54290890752, "threshold": 10485760 } } } }

 

健康端點(第二種方式)

繼承AbstractHealthIndicator抽象類,重寫doHealthCheck方法,功能比第一種要強大一點點,默認的DataSourceHealthIndicator 、 RedisHealthIndicator 都是這種寫法,內容回調中還做了異常的處理。

package com.lpf.chapter13.health; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.stereotype.Component; /** * <p>自定義健康端點</p> * <p>功能更加強大一點,DataSourceHealthIndicator / RedisHealthIndicator 都是這種寫法</p> */ @Component("my2") public class MyAbstractHealthIndicator extends AbstractHealthIndicator { private static final String VERSION = "v1.0.0"; @Override protected void doHealthCheck(Health.Builder builder) throws Exception { int code = check(); if (code != 0) { builder.down().withDetail("code", code).withDetail("version", VERSION).build(); } builder.withDetail("code", code) .withDetail("version", VERSION).up().build(); } private int check() { return 0; } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

簡單測試

啟動項目,訪問 http://localhost:8080/actuator/health 看到如下內容代表配置成功

{
  "status": "UP", "details": { "my2": { "status": "UP", "details": { "code": 0, "version": "v1.0.0" } }, "my1": {...}, "diskSpace": {...} } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
定義自己的端點

上面介紹的 infohealth 都是spring-boot-actuator內置的,真正要實現自己的端點還得通過@Endpoint、 @ReadOperation@WriteOperation@DeleteOperation

注解介紹

不同請求的操作,調用時缺少必需參數,或者使用無法轉換為所需類型的參數,則不會調用操作方法,響應狀態將為400(錯誤請求)

  • @Endpoint 構建 rest api 的唯一路徑
  • @ReadOperation GET請求,響應狀態為 200 如果沒有返回值響應 404(資源未找到)
  • @WriteOperation POST請求,響應狀態為 200 如果沒有返回值響應 204(無響應內容)
  • @DeleteOperation DELETE請求,響應狀態為 200 如果沒有返回值響應 204(無響應內容)
package com.lpf.chapter13.endpoint; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import java.util.HashMap; import java.util.Map; /** * <p>@Endpoint 是構建 rest 的唯一路徑 </p> * 顧名思義就是不同請求的操作,調用時缺少必需參數,或者使用無法轉換為所需類型的參數,則不會調用操作方法,響應狀態將為400(錯誤請求) * <P>@ReadOperation = GET 響應狀態為 200 如果沒有返回值響應 404(資源未找到) </P> * <P>@WriteOperation = POST 響應狀態為 200 如果沒有返回值響應 204(無響應內容) </P> * <P>@DeleteOperation = DELETE 響應狀態為 200 如果沒有返回值響應 204(無響應內容) </P> */ @Endpoint(id = "lpf") public class MyEndPoint { @ReadOperation public Map<String, String> hello() { Map<String, String> result = new HashMap<>(); result.put("author", "lpf"); result.put("age", "24"); result.put("email", "XXXXXXXXXX@qq.com"); return result; } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

以為這就大功告成了嗎,現實告訴我的是spring-boot默認是不認識這玩意的,得申明成一個Bean(請看 主函數

主函數
package com.lpf.chapter13; import com.lpf.chapter13.endpoint.MyEndPoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @SpringBootApplication public class Chapter13Application { public static void main(String[] args) { SpringApplication.run(Chapter13Application.class, args); } @Configuration static class MyEndpointConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint public MyEndPoint myEndPoint() { return new MyEndPoint(); } } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
測試

完成准備事項后,啟動Chapter13Application 訪問 http://localhost:8080/actuator/battcn 看到如下內容代表配置成功…

{
  "author": "lpf", "age": "24", "email": "XXXXXXXXXX@qq.com" }
  • 1
  • 2
  • 3
  • 4
  • 5

總結


參考文檔:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready

目前很多大佬都寫過關於 SpringBoot 的教程了,如有雷同,請多多包涵,本教程基於最新的 spring-boot-starter-parent:2.0.2.RELEASE編寫,包括新版本的特性都會一起介紹…

https://blog.csdn.net/liupeifeng3514/article/details/80558414

 

 

前言
主要是完成微服務的監控,完成監控治理。可以查看微服務間的數據處理和調用,當它們之間出現了異常,就可以快速定位到出現問題的地方。

springboot - version: 2.0
正文
依賴
maven 項目 在 pom.xml 文件中加入 actuator 的依賴:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
1
2
3
4
使用 Gradle 構建:

dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
}
1
2
3
配置
需要注意的是 Spring Boot 2.0 相對於上個版本, Actuator 發生很多變化,

keys 的配置改變
舊的屬性 新的屬性
endpoints.<id>.* management.endpoint.<id>.*
endpoints.cors.* management.endpoints.web.cors.*
endpoints.jmx.* management.endpoints.jmx.*
management.address management.server.address
management.context-path management.server.servlet.context-path
management.ssl.* management.server.ssl.*
management.port management.server.port
基本路徑
所有 endpoints 默認情況下都已移至 /actuator。就是多了跟路徑 actuator ;

上個版本中的 management/context-path: 和 management/port: 改為 :

management:
server:
port: 8004
servlet:
context-path: /xxx # 只有在設置了 management.server.port 時才有效
1
2
3
4
5
另外,您還可以使用新的單獨屬性 management.endpoints.web.base-path 為管理端點設置基本路徑。

例如,如果你設置management.server.servlet.context-path=/management和management.endpoints.web.base-path=/application,你就可以在下面的路徑到達終點健康:/management/application/health。

如果你想恢復 1.x 的行為(即具有/health代替/actuator/health),設置以下屬性:management.endpoints.web.base-path=/

ENDPOINTS
1.X 的時候屬性:

HTTP 方法 路徑 描述
GET /autoconfig 提供了一份自動配置報告,記錄哪些自動配置條件通過了,哪些沒通過
GET /configprops 描述配置屬性(包含默認值)如何注入Bean
GET /beans 描述應用程序上下文里全部的Bean,以及它們的關系
GET /dump 獲取線程活動的快照
GET /env 獲取全部環境屬性
GET /env/{name} 根據名稱獲取特定的環境屬性值
GET /health 報告應用程序的健康指標,這些值由HealthIndicator的實現類提供
GET /info 獲取應用程序的定制信息,這些信息由info打頭的屬性提供
GET /mappings 描述全部的URI路徑,以及它們和控制器(包含Actuator端點)的映射關系
GET /metrics 報告各種應用程序度量信息,比如內存用量和HTTP請求計數
GET /metrics/{name} 報告指定名稱的應用程序度量值
POST /shutdown 關閉應用程序,要求endpoints.shutdown.enabled設置為true
GET /trace 提供基本的HTTP請求跟蹤信息(時間戳、HTTP頭等)
2.0 部分更改:

1.x 端點 2.0 端點(改變)
/actuator 不再可用。 但是,在 management.endpoints.web.base-path 的根目錄中有一個映射,它提供了到所有暴露端點的鏈接。
/auditevents 該after參數不再需要
/autoconfig 重命名為 /conditions
/docs 不再可用
/health 現在有一個 management.endpoint.health.show-details 選項 never, always, when-authenticated,而不是依靠 sensitive 標志來確定 health 端點是否必須顯示全部細節。 默認情況下,/actuator/health公開並且不顯示細節。
/trace 重命名為 /httptrace
默認端點 path 前面多了一級 /actuator 。

同時注意只有端點/health和/info端點是暴露的。

Property Default
management.endpoints.jmx.exposure.exclude
management.endpoints.jmx.exposure.include *
management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.include info, health
1. 您可以按如下方式公開所有端點:management.endpoints.web.exposure.include=*
2. 您可以通過以下方式顯式啟用/shutdown端點:management.endpoint.shutdown.enabled=true
3. 要公開所有(已啟用)網絡端點除env端點之外:

management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env
1
2
例如:

我現在開啟所有的端點:

management:
endpoints:
web:
exposure:
include: "*" # * 在yaml 文件屬於關鍵字
1
2
3
4
5
執行 localhost:${port}/actuator,可以看到所有可以執行查看的端點監控的 Url,然后我們嘗試執行關閉應用進程的指令:shutdown:

 

端點格式
/actuator/mappings 端點大改變
JSON 格式已經更改為現在正確地包含有關上下文層次結構,多個DispatcherServlets,部署的 Servlet 和 Servlet 過濾器的信息。詳情請參閱#9979。
Actuator API 文檔的相關部分提供了一個示例文檔。

/actuator/httptrace 端點大改變
響應的結構已經過改進,以反映端點關注跟蹤 HTTP 請求 - 響應交換的情況。

總結
主要是 Spring Boot 2.0 版本升級在 Actuator 上面有許多改動,需要記錄下。

參考文章
Part V. Spring Boot Actuator: Production-ready features
Spring Boot 2.0系列文章(一):Spring Boot 2.0 遷移指南
---------------------
作者:KronChan
來源:CSDN
原文:https://blog.csdn.net/qq_35915384/article/details/80203768
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM