原文 : https://blog.csdn.net/m0_37606574/article/details/87805473

多线程异步调用的使用场景:在复杂业务逻辑中,交易链路过长,使用多线程异步服务来提高效率

1、线程池配置类

  1. import org.slf4j.Logger;
  2. import org.slf4j.LoggerFactory;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.scheduling.annotation.EnableAsync;
  6. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  7. import java.util.concurrent.ExecutorService;
  8. import java.util.concurrent.ThreadPoolExecutor;
  9. /**
  10. * 线程池配置
  11. */
  12. @Configuration
  13. @EnableAsync//开启异步调用
  14. public class ThreadExecutorConfig {
  15. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  16. /** 核心线程数 */
  17. private int corePoolSize = 10;
  18. /** 最大线程数 */
  19. private int maxPoolSize = 200;
  20. /** 队列数 */
  21. private int queueCapacity = 10;
  22. /**
  23. * @Configuration = <beans></beans>
  24. * @Bean = <bean></bean>
  25. * 返回值类型为<bean></bean>中的属性"class"对应的value
  26. * 方法名为<bean></bean>中的属性"id"对应的value
  27. * @return
  28. */
  29. @Bean
  30. public ExecutorService testFxbDrawExecutor(){
  31. logger.info("start executor testExecutor ");
  32. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  33. executor.setCorePoolSize(corePoolSize);
  34. executor.setMaxPoolSize(maxPoolSize);
  35. executor.setQueueCapacity(queueCapacity);
  36. executor.setThreadNamePrefix("test-fxb-draw-service-");
  37. // rejection-policy:当pool已经达到max size的时候,如何处理新任务
  38. // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
  39. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  40. // 执行初始化
  41. executor.initialize();
  42. return executor.getThreadPoolExecutor();
  43. }
  44. }

2、依赖注入异步服务

注:配置的 name 值,引用上面配置的方法名,即 的 id

image.png

3、实际应用中的代码(业务逻辑中的一段代码),至此已经可以在业务中使用多线程了:

  1. Future<Map> queryAcct = asyncService.submit(() -> {
  2. logger.info("--------------------1.1二类户查询------------------");
  3. return accountInfoApi.queryCardInfo(conCurrParams);
  4. });
  5. Future<String> queryCoreDate = asyncService.submit(() -> {
  6. logger.info("--------------------1.2查询核心时间------------------");
  7. return getCoreDateService.getCoreDate();
  8. });
  9. Future<Map> queryCustomCertifiedInfo = asyncService.submit(() -> {
  10. logger.info("--------------------1.3验证身份证到期日------------------");
  11. return customInfoApi.queryCustomCertifiedInfo(conCurrParams);
  12. });
  13. try {
  14. Map acctInfo = queryAcct.get();//异步调dubbo查询二类户的返回结果
  15. String coreDate = queryCoreDate.get();//异步调dubbo查询核心时间的返回结果
  16. Map customCertifiedInfo = queryCustomCertifiedInfo.get();//异步调dubbo查询身份证信息的返回结果
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }

4、代码解释:

image.png