SpringBoot手動取消接口執行方案

實際開發中經常會遇到比較耗時的接口操作,但頁面強制刷新或主動取消接口調用後後臺還是會繼續運行,特別是有大量數據庫操作時會增加服務器壓力,所以進行研究測試後總結了一套主動取消接口調用的解決方案

自定義註解用於標記耗時接口

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

自定義切面對註解的接口調用線程進行記錄

@Aspect
@Component
public class HandleCacelAspect {

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping) " +
            "|| @within(org.springframework.web.bind.annotation.PostMapping)"+
            "@annotation(org.springframework.web.bind.annotation.GetMapping) " +
            "|| @within(org.springframework.web.bind.annotation.GetMapping)")
    public void handleCacelAspect() {

    }

    @Around("handleCacelAspect()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        boolean handleCacel = false;
        Object result = null;
        try{
            HandleCancel handleCancelAnnotation = method.getAnnotation(HandleCancel.class);
            if (handleCancelAnnotation != null) {
                handleCacel = true;
            }
            if(handleCacel){
                //這裏將對應的耗時接口請求線程名稱和token關聯存儲到redis中,請安實際情況編寫
                TokenModel userModel = authService.getTokenModel();
                userModel.addThread(Thread.currentThread().getName());
                authService.updateToken(authService.getTokenString(),userModel);
            }
             result = point.proceed();
        }finally {
            if(handleCacel){
                //這裏在耗時接口執行完畢後刪除對應存儲的線程名稱,請安實際情況編寫
                TokenModel userModel = authService.getTokenModel();
                userModel.removeThread(Thread.currentThread().getName());
                authService.updateToken(authService.getTokenString(),userModel);
            }
        }

        return result;
    }
}

提供統一取消調用的接口

    @PostMapping("/killUserHandleThread")
    @ResponseBody
    public Object killUserHandleThread(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        TokenModel userModel = authService.getTokenModel();
        List<String> threadNameList = userModel.getThreadList();

        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
        int noThreads = currentGroup.activeCount();
        Thread[] lstThreads = new Thread[noThreads];
        currentGroup.enumerate(lstThreads);

        for (int i = 0; i < noThreads; i++) {
            String threadName = lstThreads[i].getName();
            if (threadNameList.contains(threadName)) {
                System.out.println("中斷線程:" + threadName);
                lstThreads[i].interrupt();
                userModel.removeThread(threadName);
                authService.updateToken(authService.getTokenString(),userModel);
            }
        }
        return result;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章