使用场景:
在项目中,当访问其他人的接口较慢或者做耗时任务时,不想程序一直卡在耗时任务上,想程序能够并行执行,我们可以使用多线程来并行的处理任务,也可以使用springboot提供的异步处理方式
启动类注解添加
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class TravelApplication /*extends SpringBootServletInitializer*/{
public static void main(String[] args) {
SpringApplication.run(TravelApplication.class, args);
}
}
只需要在对应的service上加上注解@Async
无返回值
@Async
public void first(){
try {
for(int i =0 ; i <30; i++){
Thread.sleep(10000);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("第一个:"+simpleDateFormat.format(new Date()));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
有返回值,利用future返回结果:
@Async
public Future<String> third(){
Future<String> f = null;
try {
Thread.sleep(3000);
//异步通知返回
System.out.print("执行了");
f = new AsyncResult<String>("SUCCESS!");
} catch (InterruptedException e) {
e.printStackTrace();
}
return f;
}
根据future结果判断和取值
@RequestMapping(value = "/async",method = RequestMethod.GET)
public String testAsync() throws ExecutionException, InterruptedException {
// asyncService.first();
// asyncService.second();
Future f = asyncService.third();
while (true){
System.out.println(f.isCancelled());
if(f.isCancelled()){
System.out.println("异步任务被取消了");
break;
}
if(f.isDone()){
System.out.println("异步任务执行完成,结果是:"+f.get());
break;
}
System.out.println("任务正在执行 waiting...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "test";
}
简单使用是这样的,还可以在启动类里注入 自定义线程池:
/**
* 自定义异步线程池
* @return
*/
@Bean
public AsyncTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("Anno-Executor");
executor.setMaxPoolSize(10);
// 设置拒绝策略
executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// .....
}
});
// 使用预定义的异常处理类
// executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
差不多了!!! 参考:https://my.oschina.net/u/184866/blog/1335214