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

Spring Boot 提供的端点不能知足咱们的业务需求时,咱们能够自定义一个端点。javascript

博客地址:blog.720ui.com/java

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

继承 AbstractEndpoint 抽象类

首先,咱们须要继承 AbstractEndpoint 抽象类。由于它是 Endpoint 接口的抽象实现,此外,咱们还须要重写 invoke 方法。github

值得注意的是,经过设置 @ConfigurationProperties(prefix = "endpoints.servertime"),咱们就能够在 application.properties 中经过 endpoints.servertime 配置咱们的端点。spring

@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;
    }
}复制代码

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

  • 构造方法 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 ,此时,你会服务器的当前时间。app

{
  "ms_format": 1484271566958,
  "server_time": "2017-01-13T09:39:26.958+08:00"
}复制代码

源代码

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

(完)

更多精彩文章,尽在「服务端思惟」微信公众号!

相关文章
相关标签/搜索