作者:浮尘所惑的猫猫 | 来源:互联网 | 2023-09-23 21:22
多线程异步调用的使用场景:在复杂业务逻辑中,交易链路过长,使用多线程异步服务来提高效率
1、线程池配置类
package com.fbank.dis_midware.config;
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=
* @Bean =
* 返回值类型为中的属性"class"对应的value
* 方法名为中的属性"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
4、代码解释: