Java 注释方法以启用性能跟踪
我有一个测试类,其方法名为Java 注释方法以启用性能跟踪,java,Java,我有一个测试类,其方法名为public void httpcall(),我需要获取此方法的执行时间。为了做到这一点,我在调用它之前和之后都使用了System.nanoTime()。我从这个持续时间中得到执行时间 代码段: public class Test{ public void httpcall(){ try { HttpResponse rs = HttpClientUtil.get("http://192.169.1.2:9090/pl
public void httpcall()
,我需要获取此方法的执行时间。为了做到这一点,我在调用它之前和之后都使用了System.nanoTime()
。我从这个持续时间中得到执行时间
代码段:
public class Test{
public void httpcall(){
try {
HttpResponse rs = HttpClientUtil.get("http://192.169.1.2:9090/plugins/restapi/v1/users/9223370580466120397/roster",RestOpenfire.ACCEPT, "8V9BUNA0f1gNQI3S");
} catch (Exception e) {
System.out.println("Error : "+e);
}
}
public static void main(String[] args) {
Test test=new Test();
long startTime = System.nanoTime();
test.httpcall();
long endTime = System.nanoTime();
long duration = (endTime-startTime);
System.out.println("Execution Time : "+duration);
}
}
我想做一个注释,比如@Time
,它给出了方法的执行时间,比如
@Time
public void httpcall(){
try {
HttpResponse rs = HttpClientUtil.get("http://192.169.1.2:9090/plugins/restapi/v1/users/9223370580466120397/roster",
RestOpenfire.ACCEPT, "8V9BUNA0f1gNQI3S");
} catch (Exception e) {
System.out.println("Error : " + e);
}
}
我怎样才能做到这一点?您可以尝试使用aspectj,它可以在构建过程中更改源代码,在称为编织的过程中更改.class文件,或者在运行时更改 我想,这可能是一种过度的杀伤力。 除非您有一个难以重构的庞大系统,否则我建议使用模板方法。就是
abstract class Measurable
{
protected void abstract doWork();
public void execute(){
stopWatch = StopWatch.start();
doWork();
stopWatch.stop();
System.out.println(stopWatch.getTime());
}
}
class MyHttpClient extends Measurable
{
doWork(){
HttpResponse rs = HttpClientUtil.get("http://192.169.1.2:9090/plugins/restapi/v1/users/9223370580466120397/roster",RestOpenfire.ACCEPT, "8V9BUNA0f1gNQI3S");
}
}
public static void main(String[] args) {
MyHttpClient test=new MyHttpClient();
test.execute();
}
MyHttpClient的所有使用都将调用execute()方法
还要注意,我使用了StopWatch类,因为它比使用System.currentTimeMillis更优雅和标准 注释什么都不做。它们只是元数据。您需要一个运行时框架,该框架将获取一个对象,检查对象的方法上存在的注释,调用该方法并测量它们的时间。有这样的框架。谷歌的AOP。谢谢你的建议。我可以在Spring框架中使用相同的功能吗?Spring AOP?是的,Spring有AOP支持。我甚至非常确定,已经有一些度量库插入到Spring中,并实现您想要实现的目标。