1. App上加@EnableAsync注解
@SpringCloudApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2. 定义线程池
@Configuration
public class MyConfiguration {
@Bean("taskExecutor")
public Executor taskExecutor(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);//线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
taskExecutor.setAwaitTerminationSeconds(60);//设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
taskExecutor.setCorePoolSize(4);
taskExecutor.setMaxPoolSize(8);
taskExecutor.setQueueCapacity(Integer.MAX_VALUE);//缓冲执行任务的队列
taskExecutor.setKeepAliveSeconds(60);//当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
taskExecutor.setThreadNamePrefix("kanjia-websocket-thread-");
return taskExecutor;
}
}
加入下面的设置,可以等待任务执行完成在关闭线程池
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);//线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
taskExecutor.setAwaitTerminationSeconds(60);//设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
3. 定义异步任务类,必须单独为一个类,通过@Async定义异步方法
@Component
public class Task {
@Async("taskExecutor")
public void task1() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(1000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
@Async("taskExecutor")
public void task2() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(2000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
@Async("taskExecutor")
public void task3() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(3000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
}
4. 调用异步方法
@RestController
public class HiController {
@Autowired
private Task task;
@RequestMapping(value="/hi")
public String hi() throws Exception {
long currentTimeMillis = System.currentTimeMillis();
task.task1();
task.task2();
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
return "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
}
}
访问/hi,可以看到输出:
task任务总耗时:19ms
task1任务耗时:1001ms
task2任务耗时:2039ms