webflux端点性能记录器

o75abkj4  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(684)

您知道记录springwebflux控制器端点性能以保持React性的良好实践吗?下面的原则似乎不起作用,因为它会阻止io,因为proceedingjoinpoint不返回publisher<>,它只返回一个对象

  1. @Aspect
  2. @Component
  3. @Slf4j
  4. public class LoggingAspect
  5. {
  6. //AOP expression for which methods shall be intercepted
  7. @Around("execution(* com.company.service..*(..)))")
  8. public Object profileAllMethods(ProceedingJoinPoint proceedingJoinPoint) throws Throwable
  9. {
  10. MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
  11. //Get intercepted method details
  12. String className = methodSignature.getDeclaringType().getSimpleName();
  13. String methodName = methodSignature.getName();
  14. final StopWatch stopWatch = new StopWatch();
  15. //Measure method execution time
  16. stopWatch.start();
  17. Object result = proceedingJoinPoint.proceed();
  18. stopWatch.stop();
  19. //Log method execution time
  20. log.info("Execution time of " + className + "." + methodName + " :: " + stopWatch.getTotalTimeMillis() + " ms");
  21. return result;
  22. }
  23. }
ioekq8ef

ioekq8ef1#

实际上正如在评论中提到的@toerktumlare proceedingJoinPoint.proceed() 返回对象的类型无论控制器端点返回类型是什么,因此可以保持被动的性质。注意 .subscribeOn(Schedulers.parallel()) 在这里是可选的,这是为了让我的后台代码支持并行性。为此发布解决方案:

  1. @Aspect
  2. @Component
  3. @Slf4j
  4. public class LoggingAspect
  5. {
  6. //AOP expression for which methods shall be intercepted
  7. @Around("execution(* com.company.service..*(..)))")
  8. public Object logEndpointPerformance(ProceedingJoinPoint proceedingJoinPoint) throws Throwable
  9. {
  10. MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
  11. //Get intercepted method details
  12. String className = methodSignature.getDeclaringType().getSimpleName();
  13. String methodName = methodSignature.getName();
  14. final StopWatch stopWatch = new StopWatch();
  15. //Measure method execution time
  16. stopWatch.start();
  17. Object result = proceedingJoinPoint.proceed();
  18. if(result instanceof Mono){
  19. return ((Mono)result).subscribeOn(Schedulers.parallel()).flatMap(r -> {
  20. logExecutionTime(className, methodName, stopWatch);
  21. return Mono.just(r);
  22. });
  23. }
  24. else if(result instanceof Flux){
  25. return ((Flux<Object>)result).subscribeOn(Schedulers.parallel()).collectList().flatMapMany(r -> {
  26. logExecutionTime(className, methodName, stopWatch);
  27. return Flux.fromIterable(r);
  28. });
  29. }
  30. else{
  31. logExecutionTime(className, methodName, stopWatch);
  32. return result;
  33. }
  34. }
  35. private void logExecutionTime(final String className, final String methodName, final StopWatch stopWatch){
  36. stopWatch.stop();
  37. //Log method execution time
  38. log.debug("[ " + stopWatch.getTotalTimeMillis() + " mls ] lasted execution of" + className + "." + methodName );
  39. }
  40. }
展开查看全部

相关问题