本文转自:https://www.jianshu.com/p/9fab4e81d7bb

最近在研究改写actuator的方式,这些放这里已备忘

Endpoint

SpringBoot的Endpoint主要是用来监控应用服务的运行状况,并集成在Mvc中提供查看接口。内置的Endpoint比如HealthEndpoint会监控dist和db的状况,MetricsEndpoint则会监控内存和gc的状况。
Endpoint的接口如下,其中invoke()是主要的方法,用于返回监控的内容,isSensitive()用于权限控制。

    public interface Endpoint<T> {
String getId();
boolean isEnabled();
boolean isSensitive();
T invoke();
}

Endpoint的加载还是依靠spring.factories实现的。spring-boot-actuator包下的META-INF/spring.factories配置了EndpointAutoConfiguration。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
...
org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration,\
...

EndpointAutoConfiguration就会注入必要的Endpoint。有些Endpoint需要外部的收集类,比如TraceEndpoint。

    @Bean
@ConditionalOnMissingBean
public TraceEndpoint traceEndpoint() {
return new TraceEndpoint(this.traceRepository);
}

TraceEndpoint会记录每次请求的Request和Response的状态,需要嵌入到Request的流程中,这里就主要用到了3个类。

  1. TraceRepository用于保存和获取Request和Response的状态。
    public interface TraceRepository {
List<Trace> findAll();
void add(Map<String, Object> traceInfo);
}
  1. WebRequestTraceFilter用于嵌入web request,收集请求的状态并保存在TraceRepository中。
  2. TraceEndpoint,invoke()方法直接调用TraceRepository保存的数据。
    public class TraceEndpoint extends AbstractEndpoint<List<Trace>> {
private final TraceRepository repository;
public TraceEndpoint(TraceRepository repository) {
super("trace");
Assert.notNull(repository, "Repository must not be null");
this.repository = repository;
}
public List<Trace> invoke() {
return this.repository.findAll();
}
}

Endpoint的Mvc接口主要是通过EndpointWebMvcManagementContextConfiguration实现的,这个类的配置也放在spring.factories中。

...
org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration=\
org.springframework.boot.actuate.autoconfigure.EndpointWebMvcManagementContextConfiguration,\
org.springframework.boot.actuate.autoconfigure.EndpointWebMvcHypermediaManagementContextConfiguration

EndpointWebMvcManagementContextConfiguration注入EndpointHandlerMapping来实现Endpoint的Mvc接口。

    @Bean
@ConditionalOnMissingBean
public EndpointHandlerMapping endpointHandlerMapping() {
Set<? extends MvcEndpoint> endpoints = mvcEndpoints().getEndpoints();
CorsConfiguration corsConfiguration = getCorsConfiguration(this.corsProperties);
EndpointHandlerMapping mapping = new EndpointHandlerMapping(endpoints,corsConfiguration);
boolean disabled = this.managementServerProperties.getPort() != null && this.managementServerProperties.getPort() == -1;
mapping.setDisabled(disabled);
if (!disabled) {
mapping.setPrefix(this.managementServerProperties.getContextPath());
}
if (this.mappingCustomizers != null) {
for (EndpointHandlerMappingCustomizer customizer : this.mappingCustomizers) {
customizer.customize(mapping);
}
}
return mapping;
}

自定义Endpoint

自定义Endpoint也是类似的原理。这里自定义Endpoint实现应用内存的定时收集。完整的代码放在Github上了。

  1. 收集内存,MemStatus是内存的存储结构,MemCollector是内存的收集类,使用Spring内置的定时功能,每5秒收集当前内存。
    public static class MemStatus {
public MemStatus(Date date, Map<String, Object> status) {
this.date = date;
this.status = status;
}
private Date date;
private Map<String, Object> status;
public Date getDate() {
return date;
}
public Map<String, Object> getStatus() {
return status;
}
}
    public static class MemCollector {
private int maxSize = 5;
private List<MemStatus> status;
public MemCollector(List<MemStatus> status) {
this.status = status;
}
@Scheduled(cron = "0/5 * * * * ? ")
public void collect() {
Runtime runtime = Runtime.getRuntime();
Long maxMemory = runtime.maxMemory();
Long totalMemory = runtime.totalMemory();
Map<String, Object> memoryMap = new HashMap<String, Object>(2, 1);
Date date = Calendar.getInstance().getTime();
memoryMap.put("maxMemory", maxMemory);
memoryMap.put("totalMemory", totalMemory);
if (status.size() > maxSize) {
status.remove(0);
status.add(new MemStatus(date, memoryMap));
} else {
status.add(new MemStatus(date, memoryMap));
}
}
}
  1. 自定义Endpoint,getId是EndPoint的唯一标识,也是Mvc接口对外暴露的路径。invoke方法,取出maxMemory和totalMemory和对应的时间。
    public static class MyEndPoint implements Endpoint {
private List<MemStatus> status;
public MyEndPoint(List<MemStatus> status) {
this.status = status;
}
public String getId() {
return "my";
}
public boolean isEnabled() {
return true;
}
public boolean isSensitive() {
return false;
}
public Object invoke() {
if (status == null || status.isEmpty()) {
return "hello world";
}
Map<String, List<Map<String, Object>>> result = new HashMap<String, List<Map<String, Object>>>();
for (MemStatus memStatus : status) {
for (Map.Entry<String, Object> entry : memStatus.status.entrySet()) {
List<Map<String, Object>> collectList = result.get(entry.getKey());
if (collectList == null) {
collectList = new LinkedList<Map<String, Object>>();
result.put(entry.getKey(), collectList);
}
Map<String, Object> soloCollect = new HashMap<String, Object>();
soloCollect.put("date", memStatus.getDate());
soloCollect.put(entry.getKey(), entry.getValue());
collectList.add(soloCollect);
}
}
return result;
}
}
  1. AutoConfig,注入了MyEndPoint,和MemCollector。
    public static class EndPointAutoConfig {
private List<MemStatus> status = new ArrayList<MemStatus>();
@Bean
public MyEndPoint myEndPoint() {
return new MyEndPoint(status);
}
@Bean
public MemCollector memCollector() {
return new MemCollector(status);
}
}
  1. 程序入口,运行后访问http://localhost:8080/my 就可以看到了。
    @Configuration
@EnableAutoConfiguration
public class CustomizeEndPoint { public static void main(String[] args) {
SpringApplication application = new SpringApplication(CustomizeEndPoint.class);
application.run(args);
}
}

结语

Endpoint也是通过spring.factories实现扩展功能,注入了对应的Bean来实现应用监控的功能。


作者:wcong
链接:https://www.jianshu.com/p/9fab4e81d7bb
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

深入SpringBoot:自定义Endpoint(转)的更多相关文章

  1. 深入SpringBoot:自定义Endpoint

    前言 上一篇文章介绍了SpringBoot的PropertySourceLoader,自定义了Json格式的配置文件加载.这里再介绍下EndPoint,并通过自定EndPoint来介绍实现原理. En ...

  2. SpringBoot自定义拦截器实现IP白名单功能

    SpringBoot自定义拦截器实现IP白名单功能 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8993331.html 首先,相关功能已经上线了,且先让我先 ...

  3. SpringBoot自定义错误信息,SpringBoot适配Ajax请求

    SpringBoot自定义错误信息,SpringBoot自定义异常处理类, SpringBoot异常结果处理适配页面及Ajax请求, SpringBoot适配Ajax请求 ============== ...

  4. SpringBoot自定义错误页面,SpringBoot 404、500错误提示页面

    SpringBoot自定义错误页面,SpringBoot 404.500错误提示页面 SpringBoot 4xx.html.5xx.html错误提示页面 ====================== ...

  5. springboot自定义错误页面

    springboot自定义错误页面 1.加入配置: @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { re ...

  6. SpringBoot自定义Filter

    SpringBoot自定义Filter SpringBoot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,当然我们可以自定 义F ...

  7. springboot 自定义LocaleResolver切换语言

    springboot 自定义LocaleResolver切换语言 我们在做项目的时候,往往有很多项目需要根据用户的需要来切换不同的语言,使用国际化就可以轻松解决. 我们可以自定义springboor中 ...

  8. SpringMVC拦截器与SpringBoot自定义拦截器

    首先我们先回顾一下传统拦截器的写法: 第一步创建一个类实现HandlerInterceptor接口,重写接口的方法. 第二步在XML中进行如下配置,就可以实现自定义拦截器了 SpringBoot实现自 ...

  9. [技术博客] SPRINGBOOT自定义注解

    SPRINGBOOT自定义注解 在springboot中,有各种各样的注解,这些注解能够简化我们的配置,提高开发效率.一般来说,springboot提供的注解已经佷丰富了,但如果我们想针对某个特定情景 ...

随机推荐

  1. 页面中的删除确认(ajax)、输入框中确认信息是否可用(ajax)的jquery代码

    1.页面中的删除确认(ajax) <%@ page language="java" contentType="text/html; charset=UTF-8&qu ...

  2. Python学习-34.Python中os模块的一些方法(二)

    stat方法: 用于获取文件信息,例如创建时间.文件大小等. import os filestate=os.stat("e:/temp/test.txt") print(files ...

  3. 五、搭建kube-dns

    1. 简介   kube-dns用来为kubernetes service分配子域名,在集群中可以通过名称访问service.通常kube-dns会为service赋予一个名为"servic ...

  4. Django报错:ConnectionAbortedError: [WinError 10053] 你的主机中的软件中止了一个已建立的连接。

    ajax请求时加上 async : false, $.ajax({ url:"{% url 'article:article_post' %}", {#一定不要写成小写了,坑了好久 ...

  5. C# WPF 登录多线程中 “调用线程无法访问对象,因为另一个线程拥有该对象“

    造成这个错误的原因很多,以下是我遇到的 我的思路,开启一个线程A登录.因为服务器响应登录成功需要在主线程做一些操作,我这边需要用到主线程的窗口对象,我把窗口对象传到线程 A,直接用实例方法会有这个错误 ...

  6. 《ASP.NET MVC 5 破境之道》:第一境 ASP.Net MVC5项目初探 — 第三节:View层简单改造

    第一境 ASP.Net MVC5项目初探 — 第三节:View层简单改造 MVC默认模板的视觉设计从MVC1到MVC3都没有改变,比较陈旧了:在MVC4中做了升级,好看些,在不同的分辨率下,也能工作得 ...

  7. c# 字符串去掉两端空格,并且将字符串中多个空格替换成一个空格

    字符串去掉两端空格,并且将字符串中多个空格替换成一个空格: 主要还是考察使用字符串的方法: trim(); 去掉字符串两端空格 split(); 切割 string.join(); 连接 class ...

  8. JQuery Mobile - 解决切换页面时,闪屏,白屏等问题

    在点击链接,切换页面时候,总是闪屏,感觉很别扭,看起来不舒服,怎么解决这个问题?方法很简单,就是在每个页面的meta标签内定义user-scalable的属性为 no! <meta name=& ...

  9. python 简单搭建阻塞式单进程,多进程,多线程服务

    由于经常被抓取文章内容,在此附上博客文章网址:,偶尔会更新某些出错的数据或文字,建议到我博客地址 :  --> 点击这里 我们可以通过这样子的方式去理解apache的工作原理 1 单进程TCP服 ...

  10. 解决Navicat连接Oracle时报错ORA-28547

    1:ORA-28547 原因:navicate Primium版本的OCi和本地数据库的OCI版本不一致. 解决方法: 1:把navicate Primium版本自带oci.dll替换本地Oracle ...