Spring Boot 揭秘与实战(九) 应用监控篇 - 自定义监控端点

文章目录

  1. 1. 继承 AbstractEndpoint 抽象类
  2. 2. 创建端点配置类
  3. 3. 运行
  4. 4. 源代码

Spring Boot 提供的端点不能满足我们的业务需求时,我们可以自定义一个端点。

本文,我将演示一个简单的自定义端点,用来查看服务器的当前时间,它将返回两个参数,一个是标准的包含时区的当前时间格式,一个是当前时间的时间戳格式。

继承 AbstractEndpoint 抽象类

首先,我们需要继承 AbstractEndpoint 抽象类。因为它是 Endpoint 接口的抽象实现,此外,我们还需要重写 invoke 方法。

值得注意的是,通过设置 @ConfigurationProperties(prefix = “endpoints.servertime”),我们就可以在 application.properties 中通过 endpoints.servertime 配置我们的端点。

  1. @ConfigurationProperties(prefix="endpoints.servertime")
  2. public class ServerTimeEndpoint extends AbstractEndpoint<Map<String, Object>> {
  3.  
  4. public ServerTimeEndpoint() {
  5. super("servertime", false);
  6. }
  7.  
  8. @Override
  9. public Map<String, Object> invoke() {
  10. Map<String, Object> result = new HashMap<String, Object>();
  11. DateTime dateTime = DateTime.now();
  12. result.put("server_time", dateTime.toString());
  13. result.put("ms_format", dateTime.getMillis());
  14. return result;
  15. }
  16. }

上面的代码,我解释下,两个重要的细节。

  • 构造方法 ServerTimeEndpoint,两个参数分别表示端点 ID 和是否端点默认是敏感的。我这边设置端点 ID 是 servertime,它默认不是敏感的。
  • 我们需要通过重写 invoke 方法,返回我们要监控的内容。这里我定义了一个 Map,它将返回两个参数,一个是标准的包含时区的当前时间格式,一个是当前时间的时间戳格式。

创建端点配置类

创建端点配置类,并注册我们的端点 ServerTimeEndpoint。

  1. @Configuration
  2. public class EndpointConfig {
  3. @Bean
  4. public static Endpoint<Map<String, Object>> servertime() {
  5. return new ServerTimeEndpoint();
  6. }
  7. }

运行

启动应用

  1. @RestController
  2. @EnableAutoConfiguration
  3. @ComponentScan(basePackages = { "com.lianggzone.springboot" })
  4. public class RestfulApiWebDemo {
  5.  
  6. @RequestMapping("/home")
  7. String home() {
  8. return "Hello World!";
  9. }
  10.  
  11. public static void main(String[] args) throws Exception {
  12. SpringApplication.run(RestfulApiWebDemo.class, args);
  13. }
  14. }

访问 http://localhost:8080/servertime ,此时,你会服务器的当前时间。

  1. {
  2. "ms_format": 1484271566958,
  3. "server_time": "2017-01-13T09:39:26.958+08:00"
  4. }

源代码

相关示例完整代码: springboot-action

(完)

 

微信公众号
posted @ 2017-07-27 17:16  long77  阅读(1619)  评论(0编辑  收藏  举报