SpringBoot2.0學習第六篇之Endpoint監控端點擴展


4279695-76bcf9a21406f173
image

什么是端點? 端點就是SpringBoot通過web或者jmx的方式向外部暴露應用的信息,或者上下文的信息。SpringCloud-Admin就是根據此技術來進行實現的。他們用到的技術就是@Endpoint,而不是通過自己@GetMapping之類進行實現的。下面小編就帶大家一起來學習端點的使用。學會本文后在利用前面我們講過的autoconfigure的自動化配置后,你就可以開發更高級的SpringBoot應用(非業務系統)。本教程將帶你從業務系統開發者轉變為研發系統開發者。

用過SpringBoot的同學可能知道,SpringBoot有很多監控端點,比如當我們引入健康監控組件

4279695-81ad751a7ac299d1.jpg
image-20190308190916705

系統就會自動暴露出許多,web端口供外部調用,獲取應用的信息,或者上下文的信息。

4279695-28701e19455c5459.jpg
image-20190308191019856

自定義Web端點使用到的注解

可以使用@Endpoint,@WebEndpoint,@JmxEndpoint,或者EndpointWebExtension來實現HTTP方式的端點,可以是傳統SpringMVC也可以是最新的Spring WebFlux

  • @Endpoint相當於@WebEndpoint@JmxEndpoint的整合。web和jmx方式都支持

  • @WebEndpoint 只會生成web的方式的端點監控

4279695-a6219f1e4367861b.jpg
image-20190308190517126
  • JmxEndpoint 只會生成Jmx的方式監控
4279695-38b899f4b54e5361.jpg
image-20190308183731989
Operation HTTP method
@ReadOperation GET
@WriteOperation POST
@DeleteOperation DELETE

PATH

默認的基礎路徑是/actuator,如果一個端點配置的路徑是sessions,那么它的全路徑就是/actuator/sessions

@Component
@WebEndpoint(id = "sessions")
public class MyHealthEndpoint {
  @ReadOperation
  public Info get(@Selector String name) {
    return new Info(name, "23");
  }
}

@Selector 的含義是讓這個路徑變成/actuator/sessions/{name} 我們能從路徑上獲取一個入參。

自定義管理端點路徑

management.endpoints.web.base-path = /manage

此配置會將/actuator/sessions/{name}轉換成/manage/sessions/{name}

自定義管理服務器地址

默認端口和應用的端口是一致的,但是也可以通過配置的方式改變端口

management.server.port = 8081
management.server.address = 127.0.0.1

激活端點

//激活所有的端點的web方式請求
management.endpoints.web.exposure.include=*
//關閉端點web方式
management.endpoints.web.exposure.exclude=env,beans
//激活所有的JMX方式請求
management.endpoints.jmx.exposure.include=*

跨域方式請求

//允許跨域的網址
management.endpoints.web.cors.allowed-origins=http://example.com
//允許跨域的方法
management.endpoints.web.cors.allowed-methods=GET,POST

最后跟着小編來實現一個. 私信: 006 獲取代碼地址

4279695-85cce6a25a52b2be.jpg
image-20190308191647982

總結:

最后我們來總結。

其實@WebEndpoint 就相當於聲明成一個@RestController的控制類

而請求方法分別被下面注解代替。

Operation HTTP method
@ReadOperation GET
@WriteOperation POST
@DeleteOperation DELETE

獲取本課程代碼請關注頭條號: 軟件編程指南 ,私信: 006

更多了解可以點擊小編博客: https://blog.springlearn.cn/posts/4135/


免責聲明!

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



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