Spring Boot開啟非同步任務 子執行緒
阿新 • • 發佈:2019-02-08
1.修改Spring Boot 主類
@SpringBootApplication
@EnableAsync //開啟非同步任務
public class Application {
@Bean(name="processExecutor")
public TaskExecutor workExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setThreadNamePrefix("Async-");
threadPoolTaskExecutor.setCorePoolSize(10);
threadPoolTaskExecutor.setMaxPoolSize(20);
threadPoolTaskExecutor.setQueueCapacity(600);
threadPoolTaskExecutor.afterPropertiesSet();
return threadPoolTaskExecutor;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2.定義非同步類
@Component
public class AsyncTask {
@Async("processExecutor")
public void start() {
double random = Math.random();
int sleepInt = (int) (random * 2000);
try {
Thread.sleep(sleepInt);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3.使用:
在其他類中:
@Component
public class User {
@Autowired
private AsyncTask asyncTask;
asyncTask.start();
asyncTask.start();
asyncTask.start();
@SpringBootApplication
@EnableAsync //開啟非同步任務
public class Application {
@Bean(name="processExecutor")
public TaskExecutor workExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setThreadNamePrefix("Async-");
threadPoolTaskExecutor.setCorePoolSize(10);
threadPoolTaskExecutor.setMaxPoolSize(20);
threadPoolTaskExecutor.setQueueCapacity(600);
threadPoolTaskExecutor.afterPropertiesSet();
return threadPoolTaskExecutor;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2.定義非同步類
@Component
public class AsyncTask {
@Async("processExecutor")
public void start() {
double random = Math.random();
int sleepInt = (int) (random * 2000);
try {
Thread.sleep(sleepInt);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3.使用:
在其他類中:
@Component
public class User {
@Autowired
private AsyncTask asyncTask;
asyncTask.start();
asyncTask.start();
asyncTask.start();
}
注意:ThreadPoolTaskExecutor 的使用非常重要,之前沒有配置它導致@Async無效