所谓的异步执行其实就是使用多线程的方式实现异步调用。
异步有什么好处呢?
如果一个业务逻辑执行完成需要多个步骤,也就是调用多个方法去执行,
这个时候异步执行比同步执行相应更快。不过要注意异步请求的顺序和处理结果的顺序最好一致,不然就达不到效果了。
需要在应用入口类上添加:@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;
}
}
}
/**
* 异步调用获取文章信息
*
* @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;
}
原文:https://www.cnblogs.com/wangsen/p/11656683.html