介绍
所谓的异步执行其实就是使用多线程的方式实现异步调用。
启用异步
需要在应用入口类上添加:@EnableAsync
@EnableAsync @SpringBootApplication @IntegrationComponentScan("com.ztjy") public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); }
定义一个线程池
@Configuration public class AsyncTaskPoolConfig { @Bean(name = "taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(200); executor.setQueueCapacity(50); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("taskExecutor-ws-"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return executor; } }
编写异步请求
在异步执行的方法上添加注解:@Async
Component @Log4j2 public class AsyncTask { //这里注入的是dubbo的服务,和异步请求没有多大关系 @Reference(check = false) private AuthorFacade authorFacade; /** * 获取作者信息 * * @param authorId 作者ID * @return 作者信息 */ @Async public Future<AuthorDTO> getAuthor(String authorId){ try { System.out.println("执行线程的名字:"+Thread.currentThread().getName()); return new AsyncResult<AuthorDTO>(authorFacade.getAuthor(authorId)); } catch (Exception e) { e.printStackTrace(); return null; } } }
在service里调用异步执行的方法
/** * 异步调用获取文章信息 * * @param articleId 文章ID * @return 文章信息 */ @Override public Map getArticleDetailAsync(String articleId){ //同步调用获取文章信息 ArticleDTO articleDTO = articleFacade.getArticle(articleId); //异步调用获取作者信息 Future<AuthorDTO> authorFuture = asyncTask.getAuthor(articleDTO.getAuthorId()); Map<String,Object> map=new HashMap<>(10); map.put("article",articleDTO); try{ map.put("author",authorFuture.get()); }catch (Exception e){ log.error(e.getMessage()); } return map; }