本人初學,不好的地方還請指正
1、先創建spring boot項目
2、創建異步線程類
@Configuration
@EnableAsync
public class ExecutorPool implements AsyncConfigurer{
private Logger log = LoggerFactory.getLogger(ExecutorPool.class);
@Autowired
private ThreadPoolConfig threadPoolConfig;
public Executor getAsyncExecutor(){
System.out.println("進入線程池");
ThreadPoolTaskExecutor task = new ThreadPoolTaskExecutor();
task.setCorePoolSize(threadPoolConfig.getCorePoolSize());
task.setMaxPoolSize(threadPoolConfig.getMaxPoolSize());
task.setQueueCapacity(threadPoolConfig.getQueueCapacity());
task.setKeepAliveSeconds(threadPoolConfig.getKeepAliveSeconds());
task.setThreadNamePrefix(threadPoolConfig.getThreadNamePrefix());
// 異常處理策略,當超出最大線程數時有主線程執行task,保證task不丟失
task.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
task.initialize();
System.out.println("線程池最大核心數:"+ task.getCorePoolSize() + ";最大線程數:"+task.getMaxPoolSize()+",線程隊列數:"+threadPoolConfig.getQueueCapacity());
return task;
}
// 異步中異常處理
public AsyncUncaughtExceptionHandler getAsyncExceptionHandler(){
return new AsyncUncaughtExceptionHandler(){
@Override
public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) {
System.out.println("============="+arg0.getMessage()+"===========" + arg0);
System.out.println("=============method:"+arg1.getName());
}
};
}
}
3、異步線程調用類
@Component
public class AsyncTask {
@Async
public void AsyncQueryUserName(int i){
try {
new Thread().sleep(1000);
System.out.println("task id :"+i+",線程名稱"+Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
4、實現類
@Service
public class UserServiceImpl implements UserService {
private Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private AsyncTask ssyncTask;
@Override
public String queryUserName() {
for(int i=0;i<200;i++){
ssyncTask.AsyncQueryUserName(i);
}
return "success";
}
}
這樣便實現了spring boot的異步調用,結果如下圖