把需要異步執(zhí)行的任務(wù)丟到統(tǒng)一的線程池里執(zhí)行,這個(gè)想法不錯(cuò)。springboot簡化這個(gè)的代碼。實(shí)現(xiàn)如下:
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync //開啟異步任務(wù)支持
public class TaskExcutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
// TODO Auto-generated method stub
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(20);
taskExecutor.setCorePoolSize(5);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// TODO Auto-generated method stub
return null;
}
任務(wù)類或方法
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
//@Async 寫在這里則整個(gè)類的方法都 是異步執(zhí)行
@Service
public class AsynTestService {
@Async //需要異步執(zhí)行的方法
public void asyncTest() {
for(int i = 0; i < 10;i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}