原文 : https://blog.csdn.net/m0_37606574/article/details/87805473
多线程异步调用的使用场景:在复杂业务逻辑中,交易链路过长,使用多线程异步服务来提高效率
1、线程池配置类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 线程池配置
*/
@Configuration
@EnableAsync//开启异步调用
public class ThreadExecutorConfig {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/** 核心线程数 */
private int corePoolSize = 10;
/** 最大线程数 */
private int maxPoolSize = 200;
/** 队列数 */
private int queueCapacity = 10;
/**
* @Configuration = <beans></beans>
* @Bean = <bean></bean>
* 返回值类型为<bean></bean>中的属性"class"对应的value
* 方法名为<bean></bean>中的属性"id"对应的value
* @return
*/
@Bean
public ExecutorService testFxbDrawExecutor(){
logger.info("start executor testExecutor ");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix("test-fxb-draw-service-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 执行初始化
executor.initialize();
return executor.getThreadPoolExecutor();
}
}
2、依赖注入异步服务
注:配置的 name 值,引用上面配置的方法名,即 的 id
3、实际应用中的代码(业务逻辑中的一段代码),至此已经可以在业务中使用多线程了:
Future<Map> queryAcct = asyncService.submit(() -> {
logger.info("--------------------1.1二类户查询------------------");
return accountInfoApi.queryCardInfo(conCurrParams);
});
Future<String> queryCoreDate = asyncService.submit(() -> {
logger.info("--------------------1.2查询核心时间------------------");
return getCoreDateService.getCoreDate();
});
Future<Map> queryCustomCertifiedInfo = asyncService.submit(() -> {
logger.info("--------------------1.3验证身份证到期日------------------");
return customInfoApi.queryCustomCertifiedInfo(conCurrParams);
});
try {
Map acctInfo = queryAcct.get();//异步调dubbo查询二类户的返回结果
String coreDate = queryCoreDate.get();//异步调dubbo查询核心时间的返回结果
Map customCertifiedInfo = queryCustomCertifiedInfo.get();//异步调dubbo查询身份证信息的返回结果
} catch (Exception e) {
e.printStackTrace();
}
4、代码解释: