springboot異步線程管理AsyncConfigurer


package com.common.base.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

/**
 * @Auther: tony_t_peng
 * @Date: 2020-08-10 10:06
 *
 * 支持異步線程 @Async,@Async的線程有線程池維護
 * 被@Async的方法在獨立線程調用,不能被@ControllerAdvice全局異常處理器捕獲
 * 異常需要自己手動處理
 */
@Configuration
@EnableAsync
public class BaseAsyncConfigurer implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心線程池數量,方法: 返回可用處理器的Java虛擬機的數量。
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        //最大線程數量
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*5);
        //線程池的隊列容量
        executor.setQueueCapacity(Runtime.getRuntime().availableProcessors()*2);
        //線程名稱的前綴
        executor.setThreadNamePrefix("this-excutor-");
        // setRejectedExecutionHandler:當pool已經達到max size的時候,如何處理新任務
        // CallerRunsPolicy:不在新線程中執行任務,而是由調用者所在的線程來執行
        //executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    /*異步任務中異常處理*/
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (Throwable ex, Method method, Object... params)->{
            //todo 異步方法異常處理
            System.out.println("class#method: " + method.getDeclaringClass().getName() + "#" + method.getName());
            System.out.println("type        : " + ex.getClass().getName());
            System.out.println("exception   : " + ex.getMessage());
        };
    }

}

    支持springboot使用@Async的注解,@Async的注解是另外啟一個線程去執行方法,無法被@RestControllerAdvice該注解獲取異常,異常處理需要自己手動處理。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM