Spring Boot 實現異步事件Event


一、定義事件

public class SystemItemAlgorithmEvent extends ApplicationEvent {

    @Getter
    private final SystemItemAlgorithmParam systemItemAlgorithmParam;

    public SystemItemAlgorithmEvent(SystemItemAlgorithmParam systemItemAlgorithmParam) {
        super(systemItemAlgorithmParam);
        this.systemItemAlgorithmParam = systemItemAlgorithmParam;
    }
}

二、發布事件

@Resource
private ApplicationEventPublisher eventPublisher;

eventPublisher.publishEvent(new SystemItemAlgorithmEvent(param));

三、監聽事件

@Slf4j
@Component
public class SystemItemAlgorithmListener {

    @Resource
    private LisLabSampleItemsMapper lisLabSampleItemsMapper;

    @Resource
    private LisLabTestService lisLabTestService;

    /**
     * 事務提交后監聽
     *
     * @param event
     */
    @Async(value = AsyncPoolConfig.TASK_EXECUTOR_NAME)
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, classes = SystemItemAlgorithmEvent.class)
    public void algorithmEditTrans(SystemItemAlgorithmEvent event) {
        handleEvent(event);
    }

    /**
     * 處理業務邏輯
     *
     * @param event
     */
    private void handleEvent(event){
    }

}

四、異步線程池配置

/**
 * 異步線程池配置
 */
@Configuration
@EnableAsync
public class AsyncPoolConfig implements AsyncConfigurer {

    public static final String TASK_EXECUTOR_NAME = "taskExecutor";

    @Override
    @Bean(TASK_EXECUTOR_NAME)
    public AsyncTaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心線程數(默認線程數)
        executor.setCorePoolSize(10);
        // 最大線程數
        executor.setMaxPoolSize(20);
        // 緩沖隊列數
        executor.setQueueCapacity(200);
        // 允許線程空閑時間(單位:默認為秒)
        executor.setKeepAliveSeconds(60);
        // 線程池名前綴
        executor.setThreadNamePrefix("asyncExecutor-");
        // 設置是否等待計划任務在關閉時完成
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 設置此執行器應該阻止的最大秒數
        executor.setAwaitTerminationSeconds(60);
        // 增加 TaskDecorator 屬性的配置
        executor.setTaskDecorator(new ContextDecorator());
        // 線程池對拒絕任務的處理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }


    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }


    /**
     * 任務裝飾器
     */
    class ContextDecorator implements TaskDecorator {
        @Override
        public Runnable decorate(Runnable runnable) {
            RequestAttributes context = RequestContextHolder.currentRequestAttributes();
            return () -> {
                try {
                    // 傳遞上下文
                    RequestContextHolder.setRequestAttributes(context);
                    runnable.run();
                } finally {
                    RequestContextHolder.resetRequestAttributes();
                }
            };
        }
    }
}


免責聲明!

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



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