Async的两种创建方式
注意点
1.异步方法类不要和调用类在一个类里,异步不生效
2.异步方法类必须是spring管理
3.调用异步类的类,注入异步方法类bean,进行调用
4.@bean的方式,最好指定名字,或者和配置类方法名保持一致,不然失效
原因不知道,实测过
第一种:@bean
测试的接口
@RestController
@RequestMapping("/async")
public class TestAsync {
@Autowired
private DoRun doRun;
@RequestMapping("/test")
public String test() {
System.out.println("当前线程是:" + Thread.currentThread().getName() + ",准备完成");
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("do之前");
doRun.doRun();
System.out.println("do之后");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程已经做完了");
return "ok";
}
}
配置异步线程
@Configuration
public class AsyncConfig {
@Bean(name = "dorun") //这里指定名字,默认getAsyncExecutor,如果注入bean对应不是,失效
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(2);
taskExecutor.setKeepAliveSeconds(300000);
taskExecutor.setMaxPoolSize(4);
taskExecutor.setQueueCapacity(20);
taskExecutor.setThreadNamePrefix("test001--------");
taskExecutor.initialize();
return taskExecutor;
}
}
异步做的方法类
@Component
public class DoRun {
@Async("dorun")
public void doRun(){
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("进入异步调度");
System.out.println("当前线程是:"+Thread.currentThread().getName()+",准备完成");
}
}
第二种:AsyncConfigurer
测试接口类
@RestController
@RequestMapping("/async")
public class TestAsync {
@Autowired
private DoRun doRun;
@RequestMapping("/test")
public String test() {
System.out.println("当前线程是:" + Thread.currentThread().getName() + ",准备完成");
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("do之前");
doRun.doRun();
System.out.println("do之后");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程已经做完了");
return "ok";
}
}
配置线程类
@Configuration
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(2);
taskExecutor.setKeepAliveSeconds(300000);
taskExecutor.setMaxPoolSize(4);
taskExecutor.setQueueCapacity(20);
taskExecutor.setThreadNamePrefix("test001--------ws");
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
异步做的方法类
@Component
public class DoRun {
@Async
public void doRun(){
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("进入异步调度");
System.out.println("当前线程是:"+Thread.currentThread().getName()+",准备完成");
}
}