- SpringApplication开启Async
@Slf4j
@EnableAsync
@SpringBootApplication
public class CommonApplication {
public static void main(String[] args) {
log.info("application start...");
SpringApplication.run(CommonApplication.class, args);
}
}
- 配置线程池参数
使用spring自带线程池ThreadPoolTaskExecutor处理异步任务
@Configuration
@Slf4j
public class AsyncConfig {
private ThreadPoolTaskExecutor taskExecutor;
@Bean("taskExecutor")
public Executor taskExecutor(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(10);
taskExecutor.setMaxPoolSize(20);
taskExecutor.setQueueCapacity(100);
taskExecutor.setKeepAliveSeconds(60);
taskExecutor.setThreadNamePrefix("taskExecutor-");
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.setAwaitTerminationSeconds(60);
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return taskExecutor;
}
}
- 编写异步逻辑
@Service
public class AsyncUtils {
@Async("taskExecutor")
public void doTask() throws InterruptedException {
System.out.println("处理任务");
Thread.sleep(10000);
}
}
- 调用示例
@Service
@Slf4j
public class AsyncServiceImpl implements AsyncService {
@Autowired
private AsyncUtils asyncUtils;
@Override
public void doWork() {
try {
System.out.println("开始工作");
asyncUtils.doTask();
System.out.println("结束工作");
} catch (InterruptedException e) {
log.error("thread error");
}
}
}
- 结果符合预期
|