SpringBoot自定义线程池执行异步任务

第一步注册线程池

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

第二步 开启异步 @EnableAsync

@EnableAsync
@SpringBootApplication
@MapperScan("com.****.fusionlabel.mapper")
public class FusionLabelApplication {

    public static void main(String[] args) {
        SpringApplication.run(FusionLabelApplication.class, args);
    }
}

@第三步使用 在你要使用的service层的方法上加上@Async("taskExecutor") 指明你所使用的线程池

	@Async("taskExecutor")
	public void updateLibary(List remarks){
		remarks.stream().filter(remark -> StringUtils.isNotEmpty(remark.getRevMark())).forEach( remark -> libraryMapper.updateById(remark));
	}

当你想要返回结果时你可以返回一个Future对象

	@Async("taskExecutor")
	public Future doFuture(int i){
		Future future = null;
		future = new AsyncResult("success:" + i);
		return  future;
	}

 

你可能感兴趣的:(SpringBoot自定义线程池执行异步任务)