很多业务场景只需要发送请求而不必等待结果的返回,此时就需要线程异步场景的调用。
方式一:
1.首先初始化bean:
@Configuration
public class TaskExecutorConfig {
@Qualifier("taskExecutor2")
@Bean
public TaskExecutor executor(){
ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
executor.initialize();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(5);
return executor;
}
}
2.service层写需要异步执行的业务操作,此处为了测试方便直接写controller
@Autowired
@Qualifier("taskExecutor2")
private TaskExecutor taskExecutor2;
。。。
taskExecutor2.execute((new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(5000);
System.out.println("task running ...");
} catch (Exception e) {
}
}
}
}));
Map res = new HashMap();
System.out.println("===");
res.put("result", "success");
return res;
此时会立即返回res的map,五秒钟后自动执行后台任务
此处 @Qualifier("taskExecutor2")是为了防止自动装配的歧义性
方式二:
通过
org.springframework.scheduling.annotation.Async的 @Async
@Component
@EnableAsync
public class AsyncTest_1 {
@Async
public void hello_1() throws InterruptedException {
System.out.println("hello_1开始执行");
TimeUnit.MILLISECONDS.sleep(2000);
System.out.println("hello_1执行完毕");
}
}
@Component
@EnableAsync
public class AsyncTest_2 {
@Async
public void hello_2() throws InterruptedException {
System.out.println("hello_2开始执行");
TimeUnit.MILLISECONDS.sleep(3000);
System.out.println("hello_2执行完毕");
}
}
@Component
@EnableAsync
public class AsyncTest_3 {
@Async
public void hello_3() throws InterruptedException {
System.out.println("hello_3开始执行");
TimeUnit.MILLISECONDS.sleep(5000);
System.out.println("hello_3执行完毕");
}
}
测试类:
Map map=new HashMap();
long startTime= System.currentTimeMillis();
asyncTest_3.hello_3();
asyncTest_1.hello_1();
asyncTest_2.hello_2();
long time=(System.currentTimeMillis()-startTime)/1000;
System.out.println(time);
map.put("result",true);
return map;
测试类会立即返回map结果,hello_1、hello_2、hello_3后台异步执行
首先@Async针对Spring的bean起作用,用在普通方法是无效的
必须用@EnableAsync注解使@Async生效才可以,默认是false