在 JPA 中记录查询延迟

问题描述 投票:0回答:1

我在 springboot java 应用程序中有一个 CRUD 存储库。我正在尝试测量查询表单 APP 视角的延迟并将其记录在记录器中。请问实现此目的的好优雅方法是什么? 稍后我还将使用这些日志进行监控。

目前我正在做的方式是-

long start = System.currentTimeMillis();
result = respoistoryDao.findId();
long executionTime = System.currentTimeMillis()-start;

我怎样才能做得更好?

sql spring-boot jpa latency
1个回答
0
投票

最优雅且可重用的设计是 Aspect。 (Spring AOP 文档)

首先,创建注释

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Timed {}

然后创建方面

@Slf4j
@Aspect
@Component
public class TimedAspect {

    @Around("@annotation(Timed)")
    public Object executionTimeLogger(ProceedingJoinPoint joinPoint) {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long duration = (System.currentTimeMillis() - start);
          
        log.info("Method: {} | Duration:  {}ms", joinPoint.getSignature(), duration);
        return result;
    }
}

一旦有了这两部分,只需将

@Timed
添加到任何方法签名中,它就会为您注销持续时间。

© www.soinside.com 2019 - 2024. All rights reserved.