簡體   English   中英

跟蹤 REST API 中方法執行時間的最有效方法? (Java Spring 引導應用程序,Swagger)

[英]Most efficient way to track execution time of methods in REST API? (Java Spring Boot app, Swagger)

我有一個 Java Spring 啟動 API (Swagger),我每天都有成千上萬的電話。 我想記錄這些方法的執行時間以進行分析。 我使用 Spring AOP(面向方面編程)來制作一個簡單的接口和具體的 class,它允許我使用 @TrackExecutionTime 注釋我的方法以查看運行時。 我在下面列出了代碼。 我的問題是,在日志中,我正在跟蹤方法調用時間,但是我有數千個請求,所以我需要一種“標記”每個 api 調用並記錄它的方法,這樣我就可以遵循每個 api 調用的流程. 我正在考慮生成一個隨機 # 或者這里有人有更好的建議。 所以日志目前看起來像這樣: "com.mypackage.myclassname.mymethodname. Time taken for Execution is: 100ms"

Also, My first RestController uses Swagger, so I tried to annotate the method with my @TrackTimeExecution, but we are using the swagger-codegen-maven plugin, so it reads the swagger definition yaml file and generates the "CustomerApi" and other classes/編譯時的接口。 當我嘗試在下面的 class 級別注釋時,Spring 引導應用程序編譯,但是當我在端口 8080 上本地運行應用程序並嘗試點擊我用 Z6F061E1CAD5E2783CEA0B297C43ED 注釋的端點時,什么也沒有發生。 這就像注釋破壞了 swagger 代碼生成或其他東西,所以我不得不將注釋粘貼在 customersService.getCustomers() 方法上。 這可以接受嗎? 我想我需要從 Controller 第一次被擊中時開始計時,但正如我所說,除非我犯了一些愚蠢的錯誤,否則我不能這樣做,所以我不得不把它放在下一個方法上controller 調用。 這是否會使我的 api 調用時間不准確,因為我需要在應用程序首次收到 controller 的請求時進行計時? 會喜歡這里的任何輸入...

我的端點之一的愚蠢實現,基本相同:

@RestController
@TrackExecutionTime // this fails to compile
public class CustomerApiController implements CustomerApi {
    @Autowired
    public CustomerApiController(ObjectMapper objectMapper, HttpServletRequest request) {
        this.objectMapper = objectMapper;
        this.request = request;
}

public ResponseEntity<List<Customer>> searchCustomer() {
    return new ResponseEntity<List<Customer>>(this.customerService.getCustomers(), HttpStatus.OK);

Class 記錄使用“@TrackExecutionTime”注釋的任何方法的執行時間

@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;
    }
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackExecutionTime {
}

要在 class 上使用此注釋,您必須將注釋的目標更改為 ElementType.TYPE 而不是 ElementType.METHOD。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM