Spring Boot 提供的端點不能滿足我們的業務需求時,我們可以自定義一個端點。
本文,我將演示一個簡單的自定義端點,用來查看服務器的當前時間,它將返回兩個參數,一個是標准的包含時區的當前時間格式,一個是當前時間的時間戳格式。
繼承 AbstractEndpoint 抽象類
首先,我們需要繼承 AbstractEndpoint 抽象類。因為它是 Endpoint 接口的抽象實現,此外,我們還需要重寫 invoke 方法。
值得注意的是,通過設置 @ConfigurationProperties(prefix = “endpoints.servertime”),我們就可以在 application.properties 中通過 endpoints.servertime 配置我們的端點。
- @ConfigurationProperties(prefix="endpoints.servertime")
- public class ServerTimeEndpoint extends AbstractEndpoint<Map<String, Object>> {
- public ServerTimeEndpoint() {
- super("servertime", false);
- }
- @Override
- public Map<String, Object> invoke() {
- Map<String, Object> result = new HashMap<String, Object>();
- DateTime dateTime = DateTime.now();
- result.put("server_time", dateTime.toString());
- result.put("ms_format", dateTime.getMillis());
- return result;
- }
- }
上面的代碼,我解釋下,兩個重要的細節。
- 構造方法 ServerTimeEndpoint,兩個參數分別表示端點 ID 和是否端點默認是敏感的。我這邊設置端點 ID 是 servertime,它默認不是敏感的。
- 我們需要通過重寫 invoke 方法,返回我們要監控的內容。這里我定義了一個 Map,它將返回兩個參數,一個是標准的包含時區的當前時間格式,一個是當前時間的時間戳格式。
創建端點配置類
創建端點配置類,並注冊我們的端點 ServerTimeEndpoint。
- @Configuration
- public class EndpointConfig {
- @Bean
- public static Endpoint<Map<String, Object>> servertime() {
- return new ServerTimeEndpoint();
- }
- }
運行
啟動應用
- @RestController
- @EnableAutoConfiguration
- @ComponentScan(basePackages = { "com.lianggzone.springboot" })
- public class RestfulApiWebDemo {
- @RequestMapping("/home")
- String home() {
- return "Hello World!";
- }
- public static void main(String[] args) throws Exception {
- SpringApplication.run(RestfulApiWebDemo.class, args);
- }
- }
訪問 http://localhost:8080/servertime ,此時,你會服務器的當前時間。
- {
- "ms_format": 1484271566958,
- "server_time": "2017-01-13T09:39:26.958+08:00"
- }
源代碼
相關示例完整代碼: springboot-action
(完)
