Spring封装了JDK的线程池和线程调用,并使用标签就可以开启多线程调用。
先进行一个Spring的线程池配置
@Configuration @EnableAsync public class ThreadPoolConfig implements AsyncConfigurer { @Bean @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(Runtime.getRuntime().availableProcessors()); executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 5); executor.setQueueCapacity(Runtime.getRuntime().availableProcessors() * 2); executor.setThreadNamePrefix("this-executor-"); executor.initialize(); return executor; }
@Bean
@Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } }
再编写一个Service的异步方法调用,这里是带返回值的,不带返回值的方法比较简单,这里就不举例了。
@Service @Slf4j public class ThreadTasks {
_/**
_ * 如果异步方法有返回值,一定要使用Future包装,否则无法返回 * _@return
_ * @throws _InterruptedException
_ */ @Async
public Future
最后写一个Controller,对该异步方法进行调用
@RestController public class AsyncTaskController {
@Autowired
private ThreadTasks tasks;
@GetMapping("/users-anon/useTask")
public String useSyncTask() throws InterruptedException, ExecutionException {
Future
最后运行下来,我们可以看到每次都是不同的线程执行
2020-09-21 16:33:53.027 INFO [user-center,3e635fca3d1259da,d30e8b6372922137,false] 1126 --- [this-executor-1] com.cloud.user.service.ThreadTasks : this is async task
2020-09-21 16:35:27.664 INFO [user-center,9b68efbb2c848d7b,895ed921f6c8fe03,false] 1126 --- [this-executor-2] com.cloud.user.service.ThreadTasks : this is async task