通过AOP和AspectJ统计方法执行时间

Spring Boot: Measure Execution Time using Spring AOP and AspectJ

Photo by Veri Ivanova on Unsplash
In this post, I like to document the steps followed to solve the Concern surrounding logging execution time in a Spring Boot Application using Spring-AOP(Aspect Oriented Programming) and AspectJ.

GitHub: https://github.com/shinemon/demo-spring-boot/tree/master/spring-boot-aop-aspectj

Let’s consider a simple Spring Boot Application with a Controller and Service.

Controller:

@RestController
@Slf4j
@RequestMapping(“/api”)
public class Employee {

@Autowired
private EmployeeService employeeService;

@GetMapping(value = "/get/employee/name/{id}")
public String getEmployeeName(@PathVariable String id){
    if (StringUtils.isBlank(id)){
        return null;
    }
    return employeeService.getEmployeeNameFromId(id);
}

}
Service:

@Service
@Slf4j
public class EmployeeService {

public String getEmployeeNameFromId(String id){
    return "Test Name From Service";
}

}
Aim: Calculate and Log execution time taken by a Method.

Solution (Traditional Me😀 ): find current time in milliseconds prior to method start, and subtract with current time post method execution. May be create a Util, and still we will end up several boiler plater code within our class/methods.

Better Solution:

Spring-AOP & AspectJ: Will help us to modularize our current logging Execution Time taken concern.

There are different Advice per AOP Concepts like Before, After, Around. Here we will make use of Around Advice, which helps to surround a Method Execution (Joint Point — term per AOP i.e. a point during the execution of a program.)

Create: ExecutionTimeAdvice and Around with custom Annotation (say TrackExecutionTime)

ExecutionTimeAdvice:

@Aspect
@Component
@Slf4j
@ConditionalOnExpression(“${aspect.enabled:true}”)
public class ExecutionTimeAdvice {

@Around("@annotation(com.mailshine.springboot.aop.aspectj.advise.TrackExecutionTime)")
public Object executionTime(ProceedingJoinPoint point) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object object = point.proceed();
    long endtime = System.currentTimeMillis();
    log.info("Class Name: "+ point.getSignature().getDeclaringTypeName() +". Method Name: "+ point.getSignature().getName() + ". Time taken for Execution is : " + (endtime-startTime) +"ms");
    return object;
}

}
TrackExecutionTime:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackExecutionTime {
}
Now you only need to add “@TrackExecutionTime” annotation to your desired Methods in any of your class.

Adding to our Controller & Service:

@RestController
@Slf4j
@RequestMapping(“/api”)
public class Employee {

@Autowired
private EmployeeService employeeService;

@GetMapping(value = "/get/employee/name/{id}")
@TrackExecutionTime
public String getEmployeeName(@PathVariable String id){
    if (StringUtils.isBlank(id)){
        return null;
    }
    return employeeService.getEmployeeNameFromId(id);
}

}
@Service
@Slf4j
public class EmployeeService {

@TrackExecutionTime
public String getEmployeeNameFromId(String id){
    return "Test Name From Service";
}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值