使用Spring Boot和AspectJ实现方法跟踪基础结构
了解如何使用spring boot和aspectj实现方法跟踪基础结构!最近在优锐课学习收获颇多,记录下来大家一起进步!
在我们的应用程序中,获取方法的堆栈跟踪信息可能会节省很多时间。具有输入输出参数值和方法所花费的时间可以使查找问题变得更加容易。在本文中,我们将研究如何使用spring boot,aspectj和threadlocal为方法跟踪基础结构实现起点。
在此示例中,我使用了: spring boot starter web 2.1.7
- java 1.8 +
- aspectj 1.8
- maven 3.2
1. 总览
在本教程中,我们将准备一个简单的rest服务,该服务将在书店中检索有关一本书的详细信息。然后,我们将添加一个threadlocal
模型,该模型将在整个线程生命周期中保持堆栈结构。最后,我们将增加一个方面来削减调用堆栈中的方法,以获取输入/输出参数值。让我们开始吧!
项目结构
2. maven依赖
- spring boot starter web —使用spring mvc的restful服务
- spring — 具备aspect功能
- aspectj编织者向java类引入建议
- apache commons lang —用于字符串实用程序
1 <parent> 2 <groupid>org.springframework.boot</groupid> 3 <artifactid>spring-boot-starter-parent</artifactid> 4 <version>2.1.7.release</version> 5 </parent> 6 <properties> 7 <java.version>1.8</java.version> 8 </properties> 9 <dependencies> 10 <dependency> 11 <groupid>org.springframework.boot</groupid> 12 <artifactid>spring-boot-starter-web</artifactid> 13 <version>2.1.7.release</version> 14 </dependency> 15 <dependency> 16 <groupid>org.springframework</groupid> 17 <artifactid>spring-aop</artifactid> 18 <version>5.0.9.release</version> 19 </dependency> 20 <dependency> 21 <groupid>org.aspectj</groupid> 22 <artifactid>aspectjweaver</artifactid> 23 <version>1.8.9</version> 24 </dependency> 25 <dependency> 26 <groupid>org.apache.commons</groupid> 27 <artifactid>commons-lang3</artifactid> 28 <version>3.8.1</version> 29 </dependency> 30 </dependencies>
3. 实操
创建一个spring boot应用程序
你可以使用这些模板来为逐步实现创建一个简单的spring boot application,也可以在此处直接下载最终项目。
for intellij:
for eclipse:
简单的rest service和方法
首先,我们将创建我们的服务。我们将获得书籍项目号作为输入参数,并提供书名,价格和内容信息作为服务输出。
我们将提供三个简单的服务:
priceservice:
1 package com.example.demo.service; 2 import org.springframework.stereotype.service; 3 @service 4 public class priceservice { 5 public double getprice(int itemno){ 6 switch (itemno) { 7 case 1 : 8 return 10.d; 9 case 2 : 10 return 20.d; 11 default: 12 return 0.d; 13 } 14 } 15 }
catalogueservice:
1 package com.example.demo.service; 2 import org.springframework.stereotype.service; 3 @service 4 public class catalogueservice { 5 public string getcontent(int itemno){ 6 switch (itemno) { 7 case 1 : 8 return "lorem ipsum content 1."; 9 case 2 : 10 return "lorem ipsum content 2."; 11 default: 12 return "content not found."; 13 } 14 } 15 public string gettitle(int itemno){ 16 switch (itemno) { 17 case 1 : 18 return "for whom the bell tolls"; 19 case 2 : 20 return "of mice and men"; 21 default: 22 return "title not found."; 23 } 24 } 25 }
bookinfoservice:
1 package com.example.demo.service; 2 import org.springframework.beans.factory.annotation.autowired; 3 import org.springframework.stereotype.service; 4 @service 5 public class bookinfoservice { 6 @autowired 7 priceservice priceservice; 8 @autowired 9 catalogueservice catalogueservice; 10 public string getbookinfo(int itemno){ 11 stringbuilder sb = new stringbuilder(); 12 sb.append(" title :" + catalogueservice.gettitle(itemno)); 13 sb.append(" price:" + priceservice.getprice(itemno)); 14 sb.append(" content:" + catalogueservice.getcontent(itemno)); 15 return sb.tostring(); 16 } 17 }
bookcontroller: 这是我们的rest控制器,用于创建可检索图书信息的ret服务。我们将准备一个tracemonitor
服务,以便以后打印堆栈跟踪。
1 package com.example.demo.controller; 2 import com.example.demo.service.bookinfoservice; 3 import com.example.demo.trace.tracemonitor; 4 import org.springframework.beans.factory.annotation.autowired; 5 import org.springframework.web.bind.annotation.getmapping; 6 import org.springframework.web.bind.annotation.pathvariable; 7 import org.springframework.web.bind.annotation.restcontroller; 8 @restcontroller 9 public class bookcontroller { 10 @autowired 11 bookinfoservice bookinfoservice; 12 @autowired 13 tracemonitor tracemonitor; 14 @getmapping("/getbookinfo/{itemno}") 15 public string getbookinfo(@pathvariable int itemno) { 16 try{ 17 return bookinfoservice.getbookinfo(itemno); 18 }finally { 19 tracemonitor.printtrace(); 20 } 21 } 22 }
我们的rest控制器随时可以使用。如果我们注释掉尚未实现的tracemonitor.printtrace()
方法,然后使用@springbootapplication
注释的类运行我们的应用程序:
1 package com.example.demo; 2 import org.springframework.boot.springapplication; 3 import org.springframework.boot.autoconfigure.springbootapplication; 4 @springbootapplication 5 public class demoapplication { 6 public static void main(string[] args) { 7 springapplication.run(demoapplication.class, args); 8 } 9 }
http://localhost:8080/getbookinfo/2
> title :of mice and men price:20.0 content:lorem ipsum content 2.
线程本地模型
现在,我们将准备我们的method对象,该对象将保存任何方法调用的信息。稍后,我们将准备堆栈结构和threadlocal
对象,这些对象将在线程的整个生命周期中保持堆栈结构。
method:这是我们的模型对象,它将保留有关方法执行的所有详细信息。它包含方法的输入/输出参数,该方法所花费的时间以及methodlist
对象,该对象是直接从该方法调用的方法列表。
1 package com.example.demo.util.log.standartlogger; 2 import java.util.list; 3 public class method { 4 private string methodname; 5 private string input; 6 private list<method> methodlist; 7 private string output; 8 private long timeinms; 9 public long gettimeinms() { 10 return timeinms; 11 } 12 public void settimeinms(long timeinms) { 13 this.timeinms = timeinms; 14 } 15 public string getinput() { 16 return input; 17 } 18 public void setinput(string input) { 19 this.input = input; 20 } 21 public string getoutput() { 22 return output; 23 } 24 public void setoutput(string output) { 25 this.output = output; 26 } 27 public list<method> getmethodlist() { 28 return methodlist; 29 } 30 public void setmethodlist(list<method> methodlist) { 31 this.methodlist = methodlist; 32 } 33 public string getmethodname() { 34 return methodname; 35 } 36 public void setmethodname(string methodname) { 37 this.methodname = methodname; 38 } 39 }
threadlocalvalues: 保留主要方法的跟踪信息。方法mainmethod
包含list<method>methodlist
对象,该对象包含从main方法调用的子方法。
deque<method>methodstack
是保留方法调用堆栈的对象。它贯穿线程的整个生命周期。调用子方法时,将method对象推送到methodstack
上,当子方法返回时,将从methodstack
弹出顶部的method对象。
1 package com.example.demo.util.log.standartlogger; 2 import java.util.deque; 3 public class threadlocalvalues { 4 private deque<method> methodstack; 5 private method mainmethod; 6 public threadlocalvalues() { 7 super(); 8 } 9 public method getmainmethod() { 10 return mainmethod; 11 } 12 public void setmainmethod(method mainmethod) { 13 this.mainmethod = mainmethod; 14 } 15 public deque<method> getmethodstack() { 16 return methodstack; 17 } 18 public void setmethodstack(deque<method> methodstack) { 19 this.methodstack = methodstack; 20 } 21 }
loggerthreadlocal
: 此类保留threadlocalvalues
的threadlocal
对象。该对象在线程的整个生命周期中一直存在。
1 package com.example.demo.util.log.standartlogger; 2 import java.util.arraydeque; 3 import java.util.deque; 4 public class loggerthreadlocal { 5 static final threadlocal<threadlocalvalues> threadlocal = new threadlocal<>(); 6 private loggerthreadlocal() { 7 super(); 8 } 9 public static void setmethodstack(deque<method> methodstack) { 10 threadlocalvalues threadlocalvalues = threadlocal.get(); 11 if (null == threadlocalvalues) { 12 threadlocalvalues = new threadlocalvalues(); 13 } 14 threadlocalvalues.setmethodstack(methodstack); 15 threadlocal.set(threadlocalvalues); 16 } 17 public static void setmainmethod(method mainmethod){ 18 threadlocalvalues threadlocalvalues = threadlocal.get(); 19 if (null == threadlocalvalues) { 20 threadlocalvalues = new threadlocalvalues(); 21 } 22 threadlocalvalues.setmainmethod(mainmethod); 23 threadlocal.set(threadlocalvalues); 24 } 25 public static method getmainmethod() { 26 if (threadlocal.get() == null) { 27 return null; 28 } 29 return threadlocal.get().getmainmethod(); 30 } 31 public static deque<method> getmethodstack() { 32 if (threadlocal.get() == null) { 33 setmethodstack(new arraydeque<>()); 34 } 35 return threadlocal.get().getmethodstack(); 36 } 37 }
aspect implementations:
tracemonitor: 此类是我们方面的配置类。在此类中,我们定义切入点,切面在切入点处切割代码流。我们的切入点定义了名称以单词“ service”结尾的所有类中的所有方法。
@pointcut(value = "execution(* com.example.demo.service.*service.*(..))")
pushstackinbean: 这是将在切入点中执行方法之前将当前方法推入方法堆栈的方法。
popstackinbean: 此方法将在切入点返回该方法后,删除堆栈中的top方法。
printtrace: 这是一种将以json格式打印threadlocal
值(mainmethod
)的方法。
1 package com.example.demo.trace; 2 import java.util.arraylist; 3 import com.example.demo.util.log.standartlogger.loggerthreadlocal; 4 import com.example.demo.util.log.standartlogger.method; 5 import com.fasterxml.jackson.core.jsonprocessingexception; 6 import com.fasterxml.jackson.databind.objectmapper; 7 import org.apache.commons.lang3.stringutils; 8 import org.apache.commons.lang3.exception.exceptionutils; 9 import org.aspectj.lang.joinpoint; 10 import org.aspectj.lang.annotation.afterreturning; 11 import org.aspectj.lang.annotation.aspect; 12 import org.aspectj.lang.annotation.before; 13 import org.aspectj.lang.annotation.pointcut; 14 import org.springframework.context.annotation.configuration; 15 import org.springframework.stereotype.service; 16 @aspect 17 @service 18 @configuration 19 public class tracemonitor { 20 @pointcut(value = "execution(* com.example.demo.service.*service.*(..))") 21 private void executioninservice() { 22 //do nothing, just for pointcut def 23 } 24 @before(value = "executioninservice()") 25 public void pushstackinbean(joinpoint joinpoint) { 26 pushstack(joinpoint); 27 } 28 @afterreturning(value = "executioninservice()", returning = "returnvalue") 29 public void popstackinbean(object returnvalue) { 30 popstack(returnvalue); 31 } 32 objectmapper mapper = new objectmapper(); 33 private void pushstack(joinpoint joinpoint) { 34 method m = new method(); 35 m.setmethodname(stringutils.replace(joinpoint.getsignature().tostring(), "com.example.demo.service.", "")); 36 string input = getinputparametersstring(joinpoint.getargs()); 37 m.setinput(input); 38 m.settimeinms(long.valueof(system.currenttimemillis())); 39 loggerthreadlocal.getmethodstack().push(m); 40 } 41 private string getinputparametersstring(object[] joinpointargs) { 42 string input; 43 try { 44 input = mapper.writevalueasstring(joinpointargs); 45 } catch (exception e) { 46 input = "unable to create input parameters string. error:" + e.getmessage(); 47 } 48 return input; 49 } 50 private void popstack(object output) { 51 method childmethod = loggerthreadlocal.getmethodstack().pop(); 52 try { 53 childmethod.setoutput(output==null?"": mapper.writevalueasstring(output)); 54 } catch (jsonprocessingexception e) { 55 childmethod.setoutput(e.getmessage()); 56 } 57 childmethod.settimeinms(long.valueof(system.currenttimemillis() - childmethod.gettimeinms().longvalue())); 58 if (loggerthreadlocal.getmethodstack().isempty()) { 59 loggerthreadlocal.setmainmethod(childmethod); 60 } else { 61 method parentmethod = loggerthreadlocal.getmethodstack().peek(); 62 addchildmethod(childmethod, parentmethod); 63 } 64 } 65 private void addchildmethod(method childmethod, method parentmethod) { 66 if (parentmethod != null) { 67 if (parentmethod.getmethodlist() == null) { 68 parentmethod.setmethodlist(new arraylist<>()); 69 } 70 parentmethod.getmethodlist().add(childmethod); 71 } 72 } 73 public void printtrace() { 74 try { 75 stringbuilder sb = new stringbuilder(); 76 sb.append("\n<trace>\n").append(mapper.writerwithdefaultprettyprinter().writevalueasstring(loggerthreadlocal.getmainmethod())); 77 sb.append("\n</trace>"); 78 system.out.println(sb.tostring()); 79 } catch (jsonprocessingexception e) { 80 stringutils.abbreviate(exceptionutils.getstacktrace(e), 2000); 81 } 82 } 83 }
3. 测试和打印堆栈
当我们运行spring boot应用程序并发送get请求时:
http://localhost:8080/getbookinfo/2
回复将是:
> title:of mice and men price:20.0 content:lorem ipsum content 2.
注意:如果你之前对tracemonitor.printtrace()
进行了注释,请不要忘记取消注释。
控制台输出将是:
1 <trace> 2 { 3 "methodname": "string service.bookinfoservice.getbookinfo(int)", 4 "input": "[2]", 5 "methodlist": [ 6 { 7 "methodname": "string service.contentservice.gettitle(int)", 8 "input": "[2]", 9 "output": "\"of mice and men\"", 10 "timeinms": 3 11 }, 12 { 13 "methodname": "double service.priceservice.getprice(int)", 14 "input": "[2]", 15 "output": "20.0", 16 "timeinms": 1 17 }, 18 { 19 "methodname": "string service.contentservice.getcontent(int)", 20 "input": "[2]", 21 "output": "\"lorem ipsum content 2.\"", 22 "timeinms": 0 23 } 24 ], 25 "output": "\" title :of mice and men price:20.0 content:lorem ipsum content 2.\"", 26 "timeinms": 6 27 } 28 </trace>
由于我们可以轻松跟踪方法流程:
-
getbookinfo
method is called with input 2 -
getbookinfo
callsgettitle
method with input 2 -
gettitle
returns with output "of mice and men" in 3 ms. -
getbookinfo
callsgetprice
with input 2 -
getprice
returns with output 20.0 in 1 ms. -
getbookinfo
callsgetcontent
with input 2 -
getcontent
returns with output "lorem ipsum content 2." in 0 ms. -
getbookinfo
method returns with output "title :of mice and men price:20.0 content:lorem ipsum content 2." in 6 ms.
我们的跟踪实现适用于我们简单的rest服务调用。
进一步的改进应该是:
- 如果有任何方法获得异常,则使用
@afterthrowing
处理异常。 - 具有可缓存方法的打开/关闭跟踪机制,该方法从服务或数据库中读取可跟踪方法列表。
- 使用记录器实现(sl4j)将跟踪打印到单独的日志文件中。
感谢阅读!