在实际开发场景中,不需要等待某个方法执行完成而继续往后执行,那么我们可以将这个方法加上@Async注解放入后台线程(或线程池)中异步执行。简单示例代码如下。
配置一个线程池:
@Configuration
@EnableAsync
@Slf4j
public class ThreadPoolConfig {
@Bean
public ThreadPoolTaskExecutor threadPoolExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置线程名
executor.setThreadNamePrefix("async-thread-pool-");
// 最大核心数
executor.setMaxPoolSize(20);
// 核心线程数
executor.setCorePoolSize(4);
// 线程活跃时间
executor.setKeepAliveSeconds(60);
// 队列容量
executor.setQueueCapacity(100);
// 拒绝策略
executor.setRejectedExecutionHandler((r, ec) -> {
log.info("队列已满,任务将被丢弃。。。");
});
// 所有任务结束,关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
然后在指定需要异步执行方法上加入@Async注解,并自定线程池(当然可以不指定,直接写@Async)
@Service
@Slf4j
public class AsyncDemo {
@Async("threadPoolExecutor")
public void asyncThreadExecution() {
log.info(Thread.currentThread().getName() + "异步执行");
}
}
测试案例:
@RunWith(SpringRunner.class)
@Slf4j
@SpringBootTest(classes = DemoApplication.class)
class DemoApplicationTests {
@Autowired
private AsyncDemo asyncDemo;
@Test
void asyncDemoTest(){
log.info(Thread.currentThread().getName()+"主线程请求异步执行");
asyncDemo.asyncThreadExecution();
log.info(Thread.currentThread().getName()+"主线程请求异步执行");
}
}
执行结果:
2022-02-18 15:04:36.425 INFO 16477 --- [ main] com.example.demo.DemoApplicationTests : main主线程请求异步执行asyncUpdateOrders
2022-02-18 15:04:36.431 INFO 16477 --- [ main] com.example.demo.DemoApplicationTests : main主线程请求异步执行asyncUpdateOrders
2022-02-18 15:04:36.440 INFO 16477 --- [thread--pool--1] com.example.demo.async.AsyncDemo : async--thread--pool--1异步执行
网友评论