当前位置: 代码迷 >> 综合 >> spring 异步线程池 AsyncConfigurer ThreadPoolTaskExecutor
  详细解决方案

spring 异步线程池 AsyncConfigurer ThreadPoolTaskExecutor

热度:72   发布时间:2023-10-10 05:11:19.0

1. spring框架中使用异步线程池;

2. 使用场景,比较耗时的操作,如数据统计,报表生成,可以使用多个线程进行处理,需要及时响应的处在一个线程,及时完成请求;耗时的延时操作,可以另开启一个线程进行执行,避免等待阻塞。

3. 涉及的接口及类及注解:

    AsyncConfigurer: 配置异步线程池的接口;

    ThreadPoolTaskExecutor:线程池;

    @EnableAsync:注解配置文件(@Configuration修饰java文件,并且最好实现AsyncConfigurer接口,并重写                           getAsyncExecutor方法);

    @Async:注解需要异步线程执行的方法。

4. 实例:

@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer {@Overridepublic Executor getAsyncExecutor() {ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();taskExecutor.setCorePoolSize(10);taskExecutor.setMaxPoolSize(30);taskExecutor.setQueueCapacity(2000);taskExecutor.initialize();return taskExecutor;}@Overridepublic AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {return null;}
}
@Service
public class AsyncServiceImpl {@Asyncpublic void generateReport(){System.out.println("报表线程名称:"+"["+Thread.currentThread().getName()+"]");}
}

 

@RestController
@RequestMapping("/async")
public class AsyncController {@Autowiredprivate AsyncServiceImpl asyncServiceImpl;@RequestMapping("/page")public String asyncPage(){System.out.println("报表线程名称:"+"["+Thread.currentThread().getName()+"]");asyncServiceImpl.generateReport();return "async";}}

 

  相关解决方案