San*_*ozi 6 java spring profiling spring-boot spring-restcontroller
我有复杂的@RestController方法,如下所示:
@PostMapping("{id}")
@PreAuthorize("hasRole('ADMIN')")
@Transactional
public Response handleRequest(@PathVariable("id") long id, @RequestBody @Valid Request request) {
return service.handleRequest(id, request);
}
Run Code Online (Sandbox Code Playgroud)
我们的请求处理非常慢,因此我们想检查在特定的请求处理任务上花费了多少时间。不幸的是,很多事情都是在我的方法之外完成的,例如:
有没有办法简单地测量所有这些部分?也许是一组接收跟踪消息的记录器,以便我可以在每一步结束时提取时间戳?
我现在看到的唯一方法是更改该方法以接受HttpServletRequest和HttpServletResponse并在方法主体中执行这些部分。但是那样一来,我将失去很多Spring Boot的好处。
无需更改方法来期望 HttpServletRequest。您可以使用AspectJ
使用它,您可以收集每种方法花费的时间并分析其中的数据。
创建方法计时注释
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodTiming {
}
Run Code Online (Sandbox Code Playgroud)
在您的请求中,创建一个映射,其中将保留所有方法及其所花费的时间:
public class Request {
private Map<String, Long> methodTimings = new TreeMap<String, Long>();
public void addMethodTiming(String classAndMethodName, long executionTimeMillis) {
Long value = methodTimings.get(classAndMethodName);
if (value != null) {
executionTimeMillis += value;
}
methodTimings.put(classAndMethodName, executionTimeMillis);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,创建将处理它的 Aspect 类:
@Aspect
@Component
public class MethodTimingAspect {
private static final String DOT = ".";
@Around("@annotation(MethodTiming)")
public Object timeAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
StopWatch watch = new StopWatch();
try {
watch.start();
result = joinPoint.proceed();
} finally {
watch.stop();
long executionTime = watch.getLastTaskTimeMillis();
String className = joinPoint.getTarget().getClass().getSimpleName();
String methodName = joinPoint.getSignature().getName();
String classAndMethodName = className + DOT + methodName;
Object[] methodArgs = joinPoint.getArgs();
if (methodArgs != null) {
for (Object arg : methodArgs) {
if (arg instanceof Request) {
// inject time back into Request
Request request = (Request) arg;
request.addMethodTiming(classAndMethodName, executionTime);
break;
}
}
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
最后,只需在您想要测量的方法上添加@MethodTiming:
@MethodTiming
public Request handleRequest(Request request) {
// handle the Request
return request
}
Run Code Online (Sandbox Code Playgroud)
您的请求对象在处理后将会有类似的内容
"methodTimings": {
"RequestService.handleRequest": 2610,
"AnotherRequestService.anotherMethod": 1351
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |