SpringCloud學習2-Springboot監控模塊(actuator)


前言

學習一項新技術最大的困難是什么? 是資料。讓人高興的是找到了一本系統學習Spring Cloud的教程,《Spring Cloud微服務實戰》, 接下來的學習目標將以此書順序演進。

雖然Springboot 2.0剛剛發布,鑒於當下資料都是基於1.x的,對於初學者,站在前人的肩膀上會少踩坑。因此,接下來都將采用1.5.10.RELEASE

上一節,SpringCloud入門1-服務注冊與發現(Eureka) 中已經嘗試使用了spring-boot-starter-actuator模塊中的健康檢查端點,接下來將系統的學習該模塊的功能。

Spring Boot includes a number of additional features to help you monitor and manage your application when it’s pushed to production. You can choose to manage and monitor your application using HTTP endpoints, with JMX or even by remote shell (SSH or Telnet). Auditing, health and metrics gathering can be automatically applied to your application.

引入

測試代碼: https://github.com/Ryan-Miao/actuator-demo

如同上一節中所引入的方式一樣。創建一個springboot項目,並添加依賴

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

actuator 美 ['æktʃʊˌeɪtə]

接下來,啟動項目。


 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

2018-03-04 12:15:52.611  INFO 18468 --- [           main] com.test.actuator.ActuatorApplication    : Starting ActuatorApplication on DESKTOP-4MOUU2Q with PID 18468 (D:\workspace\learn\springcloud\actuator-demo\target\classes started by Ryan in D:\workspace\learn\springcloud\actuator-demo)
2018-03-04 12:15:52.615  INFO 18468 --- [           main] com.test.actuator.ActuatorApplication    : No active profile set, falling back to default profiles: default
2018-03-04 12:15:52.709  INFO 18468 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1efee8e7: startup date [Sun Mar 04 12:15:52 CST 2018]; root of context hierarchy
2018-03-04 12:15:55.125  INFO 18468 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-03-04 12:15:55.140  INFO 18468 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-03-04 12:15:55.140  INFO 18468 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-03-04 12:15:55.265  INFO 18468 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-03-04 12:15:55.265  INFO 18468 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2588 ms
2018-03-04 12:15:55.512  INFO 18468 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-03-04 12:15:55.512  INFO 18468 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'metricsFilter' to: [/*]
2018-03-04 12:15:55.512  INFO 18468 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-04 12:15:55.512  INFO 18468 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-04 12:15:55.512  INFO 18468 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-04 12:15:55.512  INFO 18468 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-03-04 12:15:55.512  INFO 18468 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webRequestLoggingFilter' to: [/*]
2018-03-04 12:15:55.512  INFO 18468 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'applicationContextIdFilter' to: [/*]
2018-03-04 12:15:55.926  INFO 18468 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1efee8e7: startup date [Sun Mar 04 12:15:52 CST 2018]; root of context hierarchy
2018-03-04 12:15:56.004  INFO 18468 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-04 12:15:56.004  INFO 18468 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-04 12:15:56.051  INFO 18468 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-04 12:15:56.051  INFO 18468 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-04 12:15:56.097  INFO 18468 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-04 12:15:56.387  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/env/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)
2018-03-04 12:15:56.387  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/env || /env.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-03-04 12:15:56.387  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/info || /info.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-03-04 12:15:56.387  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/health || /health.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(javax.servlet.http.HttpServletRequest,java.security.Principal)
2018-03-04 12:15:56.387  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/mappings || /mappings.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-03-04 12:15:56.387  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/trace || /trace.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-03-04 12:15:56.387  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/dump || /dump.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-03-04 12:15:56.403  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/loggers/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.LoggersMvcEndpoint.get(java.lang.String)
2018-03-04 12:15:56.403  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/loggers/{name:.*}],methods=[POST],consumes=[application/vnd.spring-boot.actuator.v1+json || application/json],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.LoggersMvcEndpoint.set(java.lang.String,java.util.Map<java.lang.String, java.lang.String>)
2018-03-04 12:15:56.403  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/loggers || /loggers.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-03-04 12:15:56.403  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/autoconfig || /autoconfig.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-03-04 12:15:56.403  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/metrics/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2018-03-04 12:15:56.403  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-03-04 12:15:56.403  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/auditevents || /auditevents.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.boot.actuate.endpoint.mvc.AuditEventsMvcEndpoint.findByPrincipalAndAfterAndType(java.lang.String,java.util.Date,java.lang.String)
2018-03-04 12:15:56.403  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/configprops || /configprops.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-03-04 12:15:56.403  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/beans || /beans.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-03-04 12:15:56.403  INFO 18468 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/heapdump || /heapdump.json],methods=[GET],produces=[application/octet-stream]}" onto public void org.springframework.boot.actuate.endpoint.mvc.HeapdumpMvcEndpoint.invoke(boolean,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.io.IOException,javax.servlet.ServletException
2018-03-04 12:15:56.512  INFO 18468 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-03-04 12:15:56.512  INFO 18468 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2018-03-04 12:15:56.747  INFO 18468 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-03-04 12:15:56.747  INFO 18468 --- [           main] com.test.actuator.ActuatorApplication    : Started ActuatorApplication in 4.615 seconds (JVM running for 5.11)

可以看到url mapping多了幾個。接下來,分別看看這幾個接口的內容。

訪問這幾個接口的時候發現啥也沒有,然后看到控制台提示,這些敏感信息需要加密。所以,必須引入security模塊。

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

設置用戶名密碼:

security.user.name=admin
security.user.password=123456

然后,重啟,訪問http://localhost:8080/health 得到

{
    "status": "UP",
    "diskSpace": {
        "status": "UP",
        "total": 126702579712,
        "free": 71547412480,
        "threshold": 10485760
    }
}

端點endpoint

Actuator endpoints可以讓我們監控和與我們的應用(application)交互。Spring Boot actuator包含了大量的內置endpoints, 當然,我們也可以添加我們自己的。

如何暴露端口取決與你采用的技術。大多數應用采用HTTP監控,這時,endpoint的ID就映射為一個接口URL。比如,默認health映射為/health. (2.0貌似不是這樣,后面再看)

自帶的內置endpoint大概有這些(sensitive是指需要密碼):

ID Description Sensitive Default
actuator 提供端點基本信息,"discovery page" true
auditevents 提供審計事件信息 true
autoconfig 提供auto-configuration報告,顯示所有的自動配置項以及生效和不生效的原因 true
beans 顯示應用中所有的bean true
configprops 顯示整理過的@ConfigurationProperties true
dump 顯示線程dump信息 true
env 顯示Spring的ConfigurableEnvironment屬性 true
flyway 顯示應用的所有Flyway database遷移 true
health 顯示系統健康狀態(登陸后顯示詳細信息) false
info 顯示一些自定義信息 false
loggers 顯示和更改應用的logger配置 true
liquibase 顯示所有的Liquibase database遷移 true
metrics 顯示當前的metrics信息 true
mappings 顯示所有@RequestMapping true
shutdown 允許應用程序正常關機(默認情況下未啟用)。 true
trace 顯示跟蹤信息(默認情況下是最近的100個HTTP請求) true

如果是Spring MVC, 還有以下幾個:

ID Description Sensitive Default
docs 顯示actuator的文檔。需要引入spring-boot-actuator-docs false
heapdump 返回hprof 文件 true
jolokia 通過HTTP公開JMX bean(當Jolokia位於類路徑中時)。 true
logfile 返回日志文件的內容(如果logging.file或logging.path屬性已設置)。支持使用HTTP范圍頭來檢索部分日志文件的內容。 true

根據endpoint的作用,可以將原生endpoint分為3類

  1. 應用配置類: 獲取應用程序中加載的應用配置、環境變量、自動化配置報告等與Spring Boot應用密切相關的配置類信息。
  2. 度量指標類: 獲取應用程序運行過程中用於監控的度量指標,比如內存信息、線程池信息、HTTP請求統計等。
  3. 操作控制類:提供對應用的關閉等操作類功能。

應用配置類

由於Spring Boot為了改善傳統Spring應用復雜的配置,采用了包掃描和自動化配置機制來加載原來集中與XML的內容。雖然這樣做讓我們代碼變得簡潔,但整個應用的實例創建和依賴關系等信息都被離散到了各個配置類的注解上。這使我們分析整個應用中資源和實例的各種關系變得非常困難。而這類endpoint可以幫助我們輕松獲取一系列關於Spring配置內容的詳細報告,比如自動化配置的報告、Bean創建的報告、環境屬性的報告等。

/env: 對於密碼屬性,屬性名中包含password、secret、key這些關鍵詞,會返回**代替value。

/info: 自定義


info.app.name=spring boot demo
info.app.version=1.0

度量指標類

/metrics: 返回內存信息、線程信息、垃圾回收信息等。

{
    "mem": 437985,
    "mem.free": 342068,
    "processors": 4,
    "instance.uptime": 19821025,
    "uptime": 19812936,
    "systemload.average": -1,
    "heap.committed": 382464,
    "heap.init": 131072,
    "heap.used": 40395,
    "heap": 1846272,
    "nonheap.committed": 56848,
    "nonheap.init": 2496,
    "nonheap.used": 55521,
    "nonheap": 0,
    "threads.peak": 25,
    "threads.daemon": 21,
    "threads.totalStarted": 28,
    "threads": 23,
    "classes": 6792,
    "classes.loaded": 6843,
    "classes.unloaded": 51,
    "gc.ps_scavenge.count": 8,
    "gc.ps_scavenge.time": 98,
    "gc.ps_marksweep.count": 3,
    "gc.ps_marksweep.time": 322,
    "httpsessions.max": -1,
    "httpsessions.active": 0,
    "gauge.response.actuator": 224,
    "gauge.response.loggers": 23,
    "gauge.response.env": 12,
    "gauge.response.docs.star-star": 19,
    "gauge.response.autoconfig": 67,
    "gauge.response.trace": 17,
    "gauge.response.metrics": 8,
    "gauge.response.heapdump.root": 2656,
    "gauge.response.docs": 3,
    "gauge.response.configprops": 167,
    "gauge.response.star-star": 8,
    "counter.status.302.docs": 2,
    "counter.status.200.actuator": 1,
    "counter.status.200.loggers": 1,
    "counter.status.200.docs.star-star": 4,
    "counter.status.200.metrics": 2,
    "counter.status.200.configprops": 1,
    "counter.status.404.star-star": 5,
    "counter.status.200.autoconfig": 1,
    "counter.status.200.heapdump.root": 1,
    "counter.status.200.env": 1,
    "counter.status.200.trace": 1
}
  1. 系統信息:包括處理器數量processors,運行時間uptime和instance.uptime,系統平均負載systemload.average.
  2. mem.*: 內存概要信息。包括分配給應用的總內存數量以及當前空閑的內存數量。這些信息來自java.lang.Runtime。
  3. heap.*: 堆內存使用情況。 這些信息來自 java.lang.management.MemoryMXBean 接口中 getHeapMemoryUsage 方法獲取的 java.lang.management.MemoryUsage。
  4. nonheap. *: 非堆內存使用情況。 這些信息來自 java.lang.management.MemoryMXBean接口中ge七NonHeapMemoryUsage方法獲取的java.lang.managemen七.MemoryUsage。
  5. threads.*: 線程使用情況,包括線程數、守護線程數(daemon汃線程峰值(peak)等,這些數據均來自java.lang.management.ThreadMXBean。
  6. classes.*: 應用加載和卸載的類統計。這些數據均來自java.lang.management.ClassLoadingMXBean。
  7. gc. *: 垃圾收集器的詳細信息,包括垃圾回收次數gc.ps—scavenge.count、垃圾回收消耗時間 gc.ps _ scavenge.time、 標記-清除算法的次數 gc.psmarksweep.count、 標記-清除算法的消耗時間gc.ps_marksweep.time。這些數據均來自java.lang.managemen七.GarbageCollectorMXBean。
  8. httpsessions. * : Tomcat容 器 的會話使用情況。包括最大會話數httpsessions.max和活躍會話數httpsessions.ac巨ve。 該度量指標信息僅在引入嵌入式Tomcat作為應用容器的時候才會提供。
  9. gauge.*: HTTP請求的性能指標之 一 ,它主要用來反映 一 個絕對數值。 比如上面示例中的gauge.response.hello: 5, 它表示上一次hello請求的延遲時間為5毫秒。
  10. counter.*: HTTP 請求的性能指標之 一 ,它主要作為計 數器來使用,記錄了增加量和減少量。 上述示例中的counter.s七紅us.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 {

    @Qualifier("counterService")
    @Autowired
    private CounterService counterService;

    @RequestMapping(value = "hello", method = RequestMethod.GET)
    public String hello(){
        counterService.increment("test.hello.count");

        return counterService.toString();
    }


}

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

/health: 在spring-boot-s七arter-ac七uator模塊中自帶實現了一 些常用資源的健康指標檢測器。這些檢測器 都通過Hea巨hindicator接口實現,並且會根據依賴關系的引入實現自動化裝配, 比如下面列出的這些。

CassandraHealthIndicator,DiskSpaceHealthIndicator,DataSourceHealthIndicator,ElasticsearchHealthIndicator,JmsHealthIndicator,MailHealthIndicator,MongoHealthIndicator,RabbitHealthIndicator,RedisHealthIndicator,SolrHealthIndicator

可以通過management.health.defaults.enabled來控制上述健康檢查是否生效。

也可以自定義,



@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() {
        // 自定義健康檢查
        return 0;
    }
}

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

/trace: 該端點用來返回基本的 HTTP 跟蹤信息。 默認情況下, 跟蹤信息的存儲采用org.springfrarnework.boo七.ac七uate.trace.InMernoryTraceRepository實現的內存方式, 默認始終保留最近的100條請求記錄。

修改endpoint配置

上述的自帶屬性可以通過配置文件修改默認配置。key前綴為endpoints.*

比如,修改beansshutdown

endpoints.beans.id=springbeans
endpoints.beans.sensitive=false
endpoints.shutdown.enabled=true

默認所有的endpoint可用,除了shutdown。當然,可以是全部關閉,然后單獨打開。

endpoints.enabled=false
endpoints.info.enabled=true

可以設置全局屬性

endpoints.sensitive=true
endpoints.info.sensitive=false

設置跨域

如果想在別的域名下調用,則需要設置允許跨域。當然可以自己手動寫跨域攔截。但actuator也提供了配置文件。

endpoints.cors.allowed-origins=http://example.com
endpoints.cors.allowed-methods=GET,POST

添加自定義endpoint

配置@BeanEndpoint對象即可。

@Bean
public Endpoint myEndpoint(){
	return new Endpoint<Map<String,Object>>() {
		@Override
		public String getId() {
			return "my-endpoint";
		}

		@Override
		public boolean isEnabled() {
			return true;
		}

		@Override
		public boolean isSensitive() {
			return false;
		}

		@Override
		public Map<String,Object> invoke() {
			final Map<String, Object> dataToDisplay = new HashMap<>();
			dataToDisplay.put("some", "thing");
			dataToDisplay.put("you", "want");
			return dataToDisplay;
		}
	};
}

參考


免責聲明!

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



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