前言
在查询大批量的数据的时候,如果需要查询多个表中的数据,或者不仅查询数据库,还需要取其他的系统中查询数据,然后将所有查询到的数据一起返回,这个时候,如果是单线程查询效率慢,这个时候多线程就可以解决这个查询效率慢的问题,Springboot中提供了@Async注解,一键实现异步操作~
实战
一、@Async配置
-
异步任务配置类
@Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { /** * 异步任务线程池配置 * @return */ @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); // 设置线程初始化数量 executor.setMaxPoolSize(100); // 设置线程池最大数量 executor.setQueueCapacity(100); // 设置等待队列的大小 executor.setThreadNamePrefix("AsyncExecutorThread-"); // 设置线程名称前缀 executor.initialize(); //如果不初始化,导致找到不到执行器 return executor; } /** * 异步任务异常处理 * 如果需要自定义对异步任务的异常进行处理,则自定义异常处理(实现AsyncUncaughtExceptionHandler接口),并在这个方法返回该对象 * @return */ @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
二、实现异步任务
在需要开启异步的方法上面加上注解
@Async
表示调用该方法的时候,通过线程池获取线程去执行,如果在Class上加@Async
则表示该类的所有方法都是异步执行的方法
-
异步任务调用示例
Controller中调用service中的异步方法更新数据,并直接返回
@Slf4j @Controller @RequestMapping("/api/dashboard") public class DashboardController { @Autowired public DashboardService dashboardService; @RequestMapping(value = "/update", method = RequestMethod.PUT) @ResponseBody public Response update(DashboardLeadsDataVo vo) { dashboardService.update(vo); log.info("主线程执行完毕,返回结果") return new Response(); } }
在Service中直接定义异步方法
@Slf4j @Transactional @Service public class DashboardServiceImpl implements DashboardService