實現 AsyncConfigurer 接口 ,並給類上加上註解 @Configuration 表示這是一個配置類,@EnableAsync 開啓異步
@Configuration
@EnableAsync
public class ThreadConfig implements AsyncConfigurer {
@Override
@Bean(name = "asyncTest")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(15);
executor.setQueueCapacity(25);
executor.setBeanName("asyncTest");
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
service 層
@Service
public class AsyncTaskService {
@Async("asyncTest")
public void executeAsyncTask(int i) {
System.out.println("線程" + Thread.currentThread().getName() + " 執行異步任務:" + i);
}
}
還需要在啓動類上添加註解 @EnableAsync
@MapperScan("com.hanxs.mapper")
@EnableCaching
@SpringBootApplication
@EnableAsync
public class SpringBoot01CacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot01CacheApplication.class, args);
}
}
測試
@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncTaskServiceTest {
@Autowired
public AsyncTaskService asyncTaskService;
@Test
public void executeAsyncTask() {
for (int i = 0; i < 20; i++) {
asyncTaskService.executeAsyncTask(i);
}
}
}
輸出