Spring Boot 提供的端点不能满足我们的业务需求时,我们可以自定义一个端点。
博客地址:blog.720ui.com/
本文,我将演示一个简单的自定义端点,用来查看服务器的当前时间,它将返回两个参数,一个是标准的包含时区的当前时间格式,一个是当前时间的时间戳格式。
继承 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
(完)
更多精彩文章,尽在「服务端思维」微信公众号!