扩展JavaMelod支持自定义监控点

简介: 扩展JavaMelod支持自定义监控点

背景

一直在使用一款轻量级的APM监控工具:Javamelody。使用简单,监控数据还是挺多维度的,定期拉出来分析还是一件很有价值的事情。

但是Javamelody本身只对Http与Spring托管对象监控,还有很多我们自己的工具类或基础库没法监控起来。在阅读其部分源码后,写了一个扩展类,实现了监控项目的自定义操作。


话不多说,直接上代码:

代码

packagenet.bull.javamelody;//因MonitoringProxy类定义为了Package。此处的Package名称需要与net.bull.javamelody保持一置importlombok.extern.slf4j.Slf4j;
importnet.bull.javamelody.internal.model.Counter;
/**javamelody监控代理。在javamelody的基础上扩展部分监控项,用于一些自定义场景[或方法]的监控点。* @author heshengchao*/@Slf4jpublicclassBusMonitorProxy {
/**默认Counter 都放到Spring下面* @return*/publicstaticCountergetCounter() {
returnMonitoringProxy.getSpringCounter();
     }
/** 自定义监控点* @param monitorName 业务监控点名称* @param call 回调函数* @throws Exception */publicstaticvoidmonitor(StringmonitorName,Functioncall) {
booleansystemError=false;//主要用于标记方法执行期间是否产生的异常。try {
getCounter().bindContextIncludingCpu(monitorName);
call.call();
        }catch (Throwablee) {
systemError=true;
thrownewRuntimeException(e);
        } finally {
getCounter().addRequestForCurrentContext(systemError);
        }
    }
/** 自定义监控点【执行完成后,需要将返回值】* @param <T>* @param monitorName 业务监控点名称* @param call 回调函数* @throws Exception */publicstatic<T>TmonitorAndReturn(StringmonitorName,Callback<T>call) {
booleansystemError=false;
try {
getCounter().bindContextIncludingCpu(monitorName);
returncall.call();
        }catch (Throwablee) {
systemError=true;
thrownewRuntimeException(e);
        } finally {
getCounter().addRequestForCurrentContext(systemError);
        }
    }
/**不需要返回值的回调接口定义* @author heshengchao* @param <T>*/@FunctionalInterfacepublicstaticinterfaceFunction {
voidcall();
    }
/**需要返回值的回调接口定义* @author heshengchao* @param <T>*/@FunctionalInterfacepublicstaticinterfaceCallback<T> {
Tcall() ;
    }
}

使用示例说明

importnet.bull.javamelody.BusMonitorProxy;
publicclassBusMonitorProxyTest {
Stringurl="";
/** 验证直接监控方法 */@TestpublicvoidtestMonitor() {
BusMonitorProxy.monitor("post.url("+url+")", () -> {
// do something.        });
    }
/** 验证需要得到响应的监控 */@TestpublicvoidtestMonitorAndReturn() {
booleanresult=BusMonitorProxy.monitorAndReturn("post.url("+url+")", () -> {
// do something.returntrue;
        });
    }
}

最后效果

image.png

目录
相关文章
|
4月前
|
安全 编译器 程序员
C++对C的扩展(下)
C++对C的扩展
45 0
|
4月前
|
SQL 消息中间件 数据采集
功能特性
本文介绍日志服务主要的功能。
30 1
|
4月前
|
安全 程序员 编译器
C++对C的扩展(上)
C++对C的扩展
49 0
|
4月前
|
SQL XML JSON
Hasor【部署 04】Dataway接口配置服务扩展能力实例分享
Hasor【部署 04】Dataway接口配置服务扩展能力实例分享
98 0
|
C语言 C++ 容器
|
存储 C#
扩展按钮图标
扩展按钮图标
377 1
扩展按钮图标
EMQ
|
消息中间件 自然语言处理 Java
JMeter 扩展插件实现对自定义协议的支持
本文作为JMeter拓展开发的第四期内容,将以扩展一个简单的Apache Kafaka Producer Sampler为例,介绍如何使用JMeter扩展插件实现更完善的新协议插件。
EMQ
249 0
JMeter 扩展插件实现对自定义协议的支持
|
消息中间件 存储 关系型数据库
支持近似计算
支持近似计算
91 0
CheckListView扩展之框架修改
我之前写过一个自定义的选框列表https://www.jianshu.com/p/e4cebd5d79bc 当时我说功能就我能想到哪些就先把哪些可能需要的功能怼进去,然后在实战中,我发现它不能满足我所有的需求,所以这个框架要改。
982 0
|
Web App开发 Linux 程序员