文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

非入侵的全链路监控系统,代码实现案例分享

2024-11-30 18:18

关注

环境准备

  1. IntelliJ IDEA Community Edition
  2. jdk1.8.0_45 64位

配置信息(路径相关修改为自己的)

  1. 配置位置:Run/Debug Configurations -> VM options
  2. 配置内容:-javaagent:E:\itstack\GIT\itstack.org\itstack-demo-agent\itstack-demo-agent-06\target\itstack-demo-agent-06-1.0.0-SNAPSHOT.jar=testargs

代码示例

itstack-demo-agent-06
├── pom.xml
└── src
├── main
│ ├── java
│ │ └── org.itstack.demo.agent
│ │ ├── plugin
│ │ │ ├── impl
│ │ │ │ ├── jvm
│ │ │ │ │ ├── JvmAdvice.java
│ │ │ │ │ ├── JvmPlugin.java
│ │ │ │ │ └── JvmStack.java
│ │ │ │ └── link
│ │ │ │ ├── LinkAdvice.java
│ │ │ │ └── LinkPlugin.java
│ │ │ ├── InterceptPoint.java
│ │ │ ├── IPlugin.java
│ │ │ └── PluginFactory.java
│ │ │
│ │ ├── track
│ │ │ ├── Span.java
│ │ │ ├── TrackContext.java
│ │ │ └── TrackManager.java
│ │ └── MyAgent.java
│ └── resources
│ └── META-INF
│ └── MANIFEST.MF
└── test
└── java
└── org.itstack.demo.test
└── ApiTest.java

JvmAdvice.java


public class JvmAdvice {

@Advice.OnMethodExit()
public static void exit() {
JvmStack.printMemoryInfo();
JvmStack.printGCInfo();
}

}

JvmPlugin.java


public class JvmPlugin implements IPlugin {

@Override
public String name() {
return "jvm";
}

@Override
public InterceptPoint[] buildInterceptPoint() {
return new InterceptPoint[]{
new InterceptPoint() {
@Override
public ElementMatcher<TypeDescription> buildTypesMatcher() {
return ElementMatchers.nameStartsWith("org.itstack.demo.test");
}

@Override
public ElementMatcher<MethodDescription> buildMethodsMatcher() {
return ElementMatchers.isMethod()
.and(ElementMatchers.any())
.and(ElementMatchers.not(ElementMatchers.nameStartsWith("main")));
}
}
};
}

@Override
public Class adviceClass() {
return JvmAdvice.class;
}

}

LinkAdvice.java


public class LinkAdvice {

@Advice.OnMethodEnter()
public static void enter(@Advice.Origin("#t") String className, @Advice.Origin("#m") String methodName) {
Span currentSpan = TrackManager.getCurrentSpan();
if (null == currentSpan) {
String linkId = UUID.randomUUID().toString();
TrackContext.setLinkId(linkId);
}
TrackManager.createEntrySpan();
}

@Advice.OnMethodExit()
public static void exit(@Advice.Origin("#t") String className, @Advice.Origin("#m") String methodName) {
Span exitSpan = TrackManager.getExitSpan();
if (null == exitSpan) return;
System.out.println("链路追踪(MQ):" + exitSpan.getLinkId() + " " + className + "." + methodName + " 耗时:" + (System.currentTimeMillis() - exitSpan.getEnterTime().getTime()) + "ms");
}

}

LinkPlugin.java


public class LinkPlugin implements IPlugin {

@Override
public String name() {
return "link";
}

@Override
public InterceptPoint[] buildInterceptPoint() {
return new InterceptPoint[]{
new InterceptPoint() {
@Override
public ElementMatcher<TypeDescription> buildTypesMatcher() {
return ElementMatchers.nameStartsWith("org.itstack.demo.test");
}

@Override
public ElementMatcher<MethodDescription> buildMethodsMatcher() {
return ElementMatchers.isMethod()
.and(ElementMatchers.any())
.and(ElementMatchers.not(ElementMatchers.nameStartsWith("main")));
}
}
};
}

@Override
public Class adviceClass() {
return LinkAdvice.class;
}

}

InterceptPoint.java


public interface InterceptPoint {

//类匹配规则
ElementMatcher<TypeDescription> buildTypesMatcher();

//方法匹配规则
ElementMatcher<MethodDescription> buildMethodsMatcher();

}

IPlugin.java


public interface IPlugin {

//名称
String name();

//监控点
InterceptPoint[] buildInterceptPoint();

//拦截器类
Class adviceClass();

}

PluginFactory.java


public class PluginFactory {

public static List<IPlugin> pluginGroup = new ArrayList<>();

static {
//链路监控
pluginGroup.add(new LinkPlugin());
//Jvm监控
pluginGroup.add(new JvmPlugin());
}

}

TrackManager.java


public class TrackManager {

private static final ThreadLocal<Stack<Span>> track = new ThreadLocal<>();

private static Span createSpan() {
Stack<Span> stack = track.get();
if (stack == null) {
stack = new Stack<>();
track.set(stack);
}
String linkId;
if (stack.isEmpty()) {
linkId = TrackContext.getLinkId();
if (linkId == null) {
linkId = "nvl";
TrackContext.setLinkId(linkId);
}
} else {
Span span = stack.peek();
linkId = span.getLinkId();
TrackContext.setLinkId(linkId);
}
return new Span(linkId);
}

public static Span createEntrySpan() {
Span span = createSpan();
Stack<Span> stack = track.get();
stack.push(span);
return span;
}


public static Span getExitSpan() {
Stack<Span> stack = track.get();
if (stack == null || stack.isEmpty()) {
TrackContext.clear();
return null;
}
return stack.pop();
}

public static Span getCurrentSpan() {
Stack<Span> stack = track.get();
if (stack == null || stack.isEmpty()) {
return null;
}
return stack.peek();
}


}

MyAgent.java


public class MyAgent {

//JVM 首先尝试在代理类上调用以下方法
public static void premain(String agentArgs, Instrumentation inst) {

System.out.println("基于javaagent链路追踪{源码微信公众号:bugstack虫洞栈}");
System.out.println("==========================================================\r\n");
AgentBuilder agentBuilder = new AgentBuilder.Default();

List<IPlugin> pluginGroup = PluginFactory.pluginGroup;
for (IPlugin plugin : pluginGroup) {
InterceptPoint[] interceptPoints = plugin.buildInterceptPoint();
for (InterceptPoint point : interceptPoints) {

AgentBuilder.Transformer transformer = (builder, typeDescription, classLoader, javaModule) -> {
builder = builder.visit(Advice.to(plugin.adviceClass()).on(point.buildMethodsMatcher()));
return builder;
};
agentBuilder = agentBuilder.type(point.buildTypesMatcher()).transform(transformer).asDecorator();
}
}

//监听
AgentBuilder.Listener listener = new AgentBuilder.Listener() {
@Override
public void onDiscovery(String s, ClassLoader classLoader, JavaModule javaModule, boolean b) {

}

@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, boolean b, DynamicType dynamicType) {
System.out.println("onTransformation:" + typeDescription);
}

@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, boolean b) {

}

@Override
public void onError(String s, ClassLoader classLoader, JavaModule javaModule, boolean b, Throwable throwable) {

}

@Override
public void onComplete(String s, ClassLoader classLoader, JavaModule javaModule, boolean b) {

}

};

agentBuilder.with(listener).installOn(inst);

}

}

MANIFEST.MF

Manifest-Version: 1.0
Premain-Class: org.itstack.demo.agent.MyAgent
Can-Redefine-Classes: true

ApiTest.java

**
* 链路追踪
* VM options:
* -javaagent:E:\itstack\GIT\itstack.org\itstack-demo-agent\itstack-demo-agent-06\target\itstack-demo-agent-06-1.0.0-SNAPSHOT.jar=testargs
*
* 按需打开需要测试的模块
* 链路监控
* pluginGroup.add(new LinkPlugin());
* Jvm监控
* pluginGroup.add(new JvmPlugin());
*
* 博客:http://itstack.org
* 论坛:http://bugstack.cn
* 公众号:bugstack虫洞栈 {获取学习源码}
* create by fuzhengwei on 2019
*
*/
public class ApiTest {

public static void main(String[] args) {

//线程一
new Thread(() -> new ApiTest().http_lt1("哪咤")).start();

//线程二
new Thread(() -> {
new ApiTest().http_lt2("悟空");
}).start();

}

public void http_lt1(String name) {
try {
Thread.sleep((long) (Math.random() * 500));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("测试结果:hi1 " + name);
http_lt2(name);
}

public void http_lt2(String name) {
try {
Thread.sleep((long) (Math.random() * 500));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("测试结果:hi2 " + name);
http_lt3(name);
}

public void http_lt3(String name) {
try {
Thread.sleep((long) (Math.random() * 500));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("测试结果:hi3 " + name);
}

}

测试结果

基于javaagent链路追踪{源码微信公众号:bugstack虫洞栈}
==========================================================

onTransformation:class org.itstack.demo.test.ApiTest
测试结果:hi2 悟空
测试结果:hi1 哪咤
测试结果:hi3 悟空
链路追踪(MQ):608a1cbf-ef1f-4195-bdc7-c3729a114f8d org.itstack.demo.test.ApiTest.http_lt3 耗时:111ms
测试结果:hi2 哪咤

init: 192MB max: 2708MB used: 43MB committed: 184MB use rate: 23%
init: 2MB max: 0MB used: 13MB committed: 14MB use rate: 95%

name: PS Scavenge count:0 took:0 pool name:[PS Eden Space, PS Survivor Space]
name: PS MarkSweep count:0 took:0 pool name:[PS Eden Space, PS Survivor Space, PS Old Gen]
-------------------------------------------------------------------------------------------------
链路追踪(MQ):608a1cbf-ef1f-4195-bdc7-c3729a114f8d org.itstack.demo.test.ApiTest.http_lt2 耗时:338ms

init: 192MB max: 2708MB used: 43MB committed: 184MB use rate: 23%
init: 2MB max: 0MB used: 13MB committed: 14MB use rate: 95%

name: PS Scavenge count:0 took:0 pool name:[PS Eden Space, PS Survivor Space]
name: PS MarkSweep count:0 took:0 pool name:[PS Eden Space, PS Survivor Space, PS Old Gen]
-------------------------------------------------------------------------------------------------
测试结果:hi3 哪咤
链路追踪(MQ):2f28ed75-650a-4f0f-bd69-fe0709a8985e org.itstack.demo.test.ApiTest.http_lt3 耗时:221ms

init: 192MB max: 2708MB used: 43MB committed: 184MB use rate: 23%
init: 2MB max: 0MB used: 13MB committed: 14MB use rate: 95%

name: PS Scavenge count:0 took:0 pool name:[PS Eden Space, PS Survivor Space]
name: PS MarkSweep count:0 took:0 pool name:[PS Eden Space, PS Survivor Space, PS Old Gen]
-------------------------------------------------------------------------------------------------
链路追踪(MQ):2f28ed75-650a-4f0f-bd69-fe0709a8985e org.itstack.demo.test.ApiTest.http_lt2 耗时:316ms

init: 192MB max: 2708MB used: 43MB committed: 184MB use rate: 23%
init: 2MB max: 0MB used: 13MB committed: 14MB use rate: 95%

name: PS Scavenge count:0 took:0 pool name:[PS Eden Space, PS Survivor Space]
name: PS MarkSweep count:0 took:0 pool name:[PS Eden Space, PS Survivor Space, PS Old Gen]
-------------------------------------------------------------------------------------------------
链路追踪(MQ):2f28ed75-650a-4f0f-bd69-fe0709a8985e org.itstack.demo.test.ApiTest.http_lt1 耗时:547ms

init: 192MB max: 2708MB used: 43MB committed: 184MB use rate: 23%
init: 2MB max: 0MB used: 13MB committed: 14MB use rate: 95%

name: PS Scavenge count:0 took:0 pool name:[PS Eden Space, PS Survivor Space]
name: PS MarkSweep count:0 took:0 pool name:[PS Eden Space, PS Survivor Space, PS Old Gen]
-------------------------------------------------------------------------------------------------

Process finished with exit code 0


来源:今日头条内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯