本文转自: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. TraceEndpointinvoke()方法直接调用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,getIdEndPoint的唯一标识,也是Mvc接口对外暴露的路径。invoke方法,取出maxMemorytotalMemory和对应的时间。
    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. D3 drag

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. Regex Golf练习笔记(1)

    正则表达式进阶练习:https://alf.nu/RegexGolf  (此练习笔记) 正则表达式验证:https://regexr.com/ (1) (2) 注释:每个词的三个字母在后面重复出现了一 ...

  3. 一个简单的QQ隐藏图生成算法

    隐藏图不是什么新鲜的东西,具体表现在大部分社交软件中,预览图看到的是一张图,而点开后看到的又是另一张图.虽然很早就看到过这类图片,但是一直没有仔细研究过它的原理,今天思考了一下,发现挺有趣的,所以自己 ...

  4. 解决 EntityFrameworkCore 执行 Add-Migration命令提示无法识别转义符的错误

    版本.asp.net core 2.0   EntityFrameworkCore2,0,. 之前执行Add-Migration 命令 提示无法识别的转义序列,各种不成功, 解决办法,找到 项目里面的 ...

  5. 在Windows安装Reids 详解

    今天安装了redis,记录点经验 因为Redis项目没有正式支持Windows. 但Microsoft开发和维护一个针对Windows 64版的redis. 下载地址在微软的GitHub上,地址:ht ...

  6. mybatis 关联表查询

    这段时间由于项目上的需求:需要将数据库中两表关联的数据查询出来展示到前端(包含一对一,一对多): (1)一对一: 在实体类中维护了另一个类的对象: 这里我以用户(User)和产品(Product)为例 ...

  7. django.db.utils.InternalError: (1050, "Table 'tb_content' already exists")

    在goods应用里面写了tb_content数据表的模型类(不该写在这里的),进行了数据迁移,还导入了数据. 在contents应用里也写了tb_content数据表的模型类(应该写在这里的), 解决 ...

  8. 解决Mysql Workbench的Error Code: 1175错误 无法删除数据

    使用workbench,如果你要批量更新或删除数据,一般会报“ Error Code: 1175 You are using safe update mode and you tried to upd ...

  9. 关于editplus设置java和c#

    1.java设置 首先要在目录上手动新建一个class文件.放置编译好的class文件

  10. ThreadLocal的实现机制

    TLS(Thread Local Storage)通过分配更多内存来解决多线程对临界资源访问的互斥问题,即每个线程均自己的临界资源对象, 这样也就不会发生访问冲突,也不需要锁机制控制,比较典型的以空间 ...