- 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;
/**
* spring 自带线程池
* @return
*/
@Bean("taskExecutor")
public Executor taskExecutor(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
// 核心线程数
taskExecutor.setCorePoolSize(10);
// 最大线程数
taskExecutor.setMaxPoolSize(20);
// 队列容量
taskExecutor.setQueueCapacity(100);
// 线程空闲时间
taskExecutor.setKeepAliveSeconds(60);
// 线程名前缀
taskExecutor.setThreadNamePrefix("taskExecutor-");
// 用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean,这样这些异步任务的销毁就会先于Redis线程池的销毁
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");
}
}
}
- 结果符合预期
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)