模擬場景:
1.一個方法中如果需要調用多個服務,如果使用傳統同步的方法會讓用戶等待太久。
2.這時,我們需要開多個線程來完成各種微服務得調用。這會大大降低用戶等待的時間。
3.但是,如果這個方法還涉及到高並發的場景,會導致不斷開線程,導致系統資源很容易撐爆得情況。
為解決以上場景出現的問題,使用線程池是比較有效的解決方案,以下介紹spring boot中配置線程池得簡單配置如使用方案
1.在src/main/resources/application.properties 添加對應配置信息
gmall.pool.coreSize=8 #池的核心大小, gmall.pool.maximumPoolSize=100 #池的最大線程數, gmall.pool.queueSize=1000000 #池的隊列長度,超出隊列以外的請求拒絕
2.添加線程池配置文件 src\main\java\[XXX包]\config\ThreadPoolConfig.java
/**
* 配置當前系統的線程池信息
*/
@Configuration
public class ThreadPoolConfig {
@Value("${gmall.pool.coreSize}")
private Integer coreSize;
@Value("${gmall.pool.maximumPoolSize}")
private Integer maximumPoolSize;
@Value("${gmall.pool.queueSize}")
private Integer queueSize;
//核心業務線程池
@Bean("mainThreadPoolExecutor")
public ThreadPoolExecutor mainThreadPoolExecutor(PoolProperties poolProperties){
/**
* public ThreadPoolExecutor(int corePoolSize,
* int maximumPoolSize,
* long keepAliveTime,
* TimeUnit unit,
* BlockingQueue<Runnable> workQueue,
* RejectedExecutionHandler handler) {
*/
LinkedBlockingDeque<Runnable> deque = new LinkedBlockingDeque<>(poolProperties.getQueueSize());
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(poolProperties.getCoreSize(),
poolProperties.getMaximumPoolSize(), 10,
TimeUnit.MINUTES, deque);
return threadPoolExecutor;
}
// 非核心業務線程池
@Bean("otherThreadPoolExecutor")
public ThreadPoolExecutor otherThreadPoolExecutor(PoolProperties poolProperties){
LinkedBlockingDeque<Runnable> deque = new LinkedBlockingDeque<>(poolProperties.getQueueSize());
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(poolProperties.getCoreSize(),
poolProperties.getMaximumPoolSize(), 10,
TimeUnit.MINUTES, deque);
return threadPoolExecutor;
}
}
3.在控制器中調用
@RestController
public class ProductItemController {
@Qualifier("mainThreadPoolExecutor")
@Autowired
ThreadPoolExecutor threadPoolExecutor;
@Qualifier("otherThreadPoolExecutor")
@Autowired
ThreadPoolExecutor otherThreadPoolExecutor;
/**
* 數據庫(商品的基本信息表、商品的屬性表、商品的促銷表)和 es(info/attr/sale)
*
* 查加緩存
* 1、第一次查。肯定長。
* @return
*/
public EsProduct productInfo2(Long id){
CompletableFuture.supplyAsync(()->{
return "";
},threadPoolExecutor).whenComplete((r,e)->{
System.out.println("處理結果"+r);
System.out.println("處理異常"+e);
});
//1、商品基本數據(名字介紹等) 100ms 異步
//2、商品的屬性數據 300ms
//3、商品的營銷數據 SmsService 1s 500ms
//4、商品的配送數據 WuliuService 2s 700ms
//5、商品的增值服務數據 SaleService 1s 1s
//otherThreadPoolExecutor.submit()
return null;
}
}
