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

时间:2023-03-09 23:42:03
Spring Boot 揭秘与实战(九) 应用监控篇 - 自定义监控端点

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. public ServerTimeEndpoint() {
  4. super("servertime", false);
  5. }
  6. @Override
  7. public Map<String, Object> invoke() {
  8. Map<String, Object> result = new HashMap<String, Object>();
  9. DateTime dateTime = DateTime.now();
  10. result.put("server_time", dateTime.toString());
  11. result.put("ms_format", dateTime.getMillis());
  12. return result;
  13. }
  14. }

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

  • 构造方法 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. @RequestMapping("/home")
  6. String home() {
  7. return "Hello World!";
  8. }
  9. public static void main(String[] args) throws Exception {
  10. SpringApplication.run(RestfulApiWebDemo.class, args);
  11. }
  12. }

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

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

源代码

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

(完)

如果觉得我的文章对你有帮助,请随意打赏。

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