欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot的@EnableAsync和@Async注解分析

 更新時(shí)間:2023年07月18日 09:57:08   作者:七月J  
這篇文章主要介紹了SpringBoot的@EnableAsync和@Async注解分析,Spring Boot是一個(gè)快速開發(fā)框架,可以幫助開發(fā)人員快速構(gòu)建基于Spring的應(yīng)用程序,需要的朋友可以參考下

前言

使用多線程,往往是創(chuàng)建Thread,或者是實(shí)現(xiàn)Runnable接口,用到線程池得時(shí)候需要?jiǎng)?chuàng)建Executors,通過使用@EnableAsync注解就可以使用多線程,@Async注解加在線程任務(wù)的方法上 可以異步執(zhí)行任務(wù)。使用 ThreadPoolTaskExecutor 就可以使用線程池。

定義配置類

這個(gè)配置類需要實(shí)現(xiàn)AsyncConfigurer接口,并實(shí)現(xiàn)他的方法

  • 異步線程的提供者,在里面配置自動(dòng)執(zhí)行的東西,如線程池參數(shù)。
  • 線程異常的處理。
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {
    private static final Logger log = LoggerFactory.getLogger(ThreadPoolConfig.class);
    @Autowired
    private ThreadPoolParamsConfig threadPoolParamsConfig;
    @Override
    @Bean("taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolParamsConfig.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolParamsConfig.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolParamsConfig.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolParamsConfig.getKeepAliveSeconds());
        executor.setThreadNamePrefix("authority-manage-thread-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex,method,params) -> {
          log.error("異常信息:{}",ex.getMessage());
          log.error("exception method:{}",method.getName());
        };
    }
}

線程池配置類

@Data
@Component
@ConfigurationProperties(prefix = "task.pool")
public class ThreadPoolParamsConfig {
    /**
     * 核心線程數(shù)
     */
    private int corePoolSize;
    /**
     * 最大線程數(shù)
     */
    private int maxPoolSize;
    /**
     * 線程空閑空間
     */
    private int keepAliveSeconds;
    /**
     * 任務(wù)隊(duì)列容量
     */
    private int queueCapacity;
}

調(diào)用異步線程任務(wù)

/**
 * 測(cè)試異步創(chuàng)建任務(wù)
 * @return
 */
public Result createIsueTask() {
    inspPlanRlnToolService.asynsBatchCreateIsueTasks();
    return Result.ok();
}

線程任務(wù)類

/**
 * 異步創(chuàng)建任務(wù)
 */
@Async("taskExecutor")
@Override
public void asynsBatchCreateIsueTasks() {
    log.info("這是一個(gè)異步任務(wù)");
}

到此這篇關(guān)于SpringBoot的@EnableAsync和@Async注解分析的文章就介紹到這了,更多相關(guān)SpringBoot的@EnableAsync內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論