Spring Boot 揭秘与实战(九) 应用监控篇 - 自定义监控端点
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
(完)

分类:
SpringBoot
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期