如何在不同的 类 中启动和停止计时器?

How can I start and stop a timer in different classes?

我想测量从传入 HTTP 请求开始到应用程序到达某个点的时间。这两个时间点位于不同的 类。我将如何从这些不同的 类 启动和停止计时器。我没有看到使用 MeterRegistry 中的 'named' 计时器的方法。

我该怎么做?

您可以按如下方式使用 AOP :

@Aspect
@Component
public class ControllerMonitor {

    protected static  final Logger LOGGER = LoggerFactory.getLogger(ControllerMonitor.class);


    @Before("execution(public * com.demo.controller.*Controller.*(..))")
    public void logBeforeAccess(JoinPoint joinPoint) {
        if(joinPoint!=null){
            String packageName = joinPoint.getSignature()!=null?joinPoint.getSignature().getDeclaringTypeName():"LOG-404";
            LOGGER.info(". . .A request initiated from controller [" + packageName + "."+ getMethodSignature(joinPoint) +  "]. . .");
        }

    }

    @After("execution(public * com.demo.controller.*Controller.*(..))")
    public void logAfterAccess(JoinPoint joinPoint) {
        if(joinPoint!=null){
            String packageName = joinPoint.getSignature()!=null?joinPoint.getSignature().getDeclaringTypeName():"LOG-404";
            LOGGER.info(". . .Request from controller [" + packageName + "."+ getMethodSignature(joinPoint) +  "] completed. . .");
        }
    }

    @AfterThrowing(pointcut = "execution(public * com.demo.controller.*Controller.*(..))",throwing="exception")
    public void logAfterThrowing(Exception exception){
        LOGGER.error("Exception caught:"+ exception.getMessage());
    }

    private String getMethodSignature(JoinPoint joinPoint){
        if(joinPoint!=null){
            String methodName = joinPoint.getSignature().getName();
            Object[] arguments = joinPoint.getArgs();
            StringBuilder sb=new StringBuilder();
            if(arguments!=null){
                for (Object param: arguments) {
                    sb.append(param).append(",");
                }
                sb =(sb.length()>1)?sb.deleteCharAt(sb.length()-1):sb;
            }
            methodName = methodName+"("+new String(sb)+")";
            return methodName;
        }else{
            return "LOG-405";
        }
    }
}

使用AOP ......无需在每个class级别上进行更改。将是一处配置..