如何为async-http-client设置执行器及线程池大小?
如何在AsyncHttpClient 2.12.3中配置自定义线程池(限制线程数为10)
你可以通过DefaultAsyncHttpClientConfig.Builder的setExecutorService()方法,传入自定义的固定大小线程池来实现需求。具体实现如下:
- 创建固定线程数为10的线程池,同时可通过
ThreadFactory设置统一的线程命名规则 - 将自定义线程池传入AsyncHttpClient的配置中
完整代码示例:
// 创建固定10线程的自定义线程池,设置线程名前缀 ExecutorService customExecutor = Executors.newFixedThreadPool(10, r -> { Thread thread = new Thread(r); thread.setName("CustomThreadPool-" + thread.getId()); return thread; }); // 初始化AsyncHttpClient并绑定自定义线程池 final AsyncHttpClient http = asyncHttpClient( config() .setExecutorService(customExecutor) .setThreadPoolName("CustomThreadPool") // 保留线程池标识配置 );
注意事项
- 若希望AsyncHttpClient关闭时自动销毁线程池,可使用重载方法传入
true让客户端管理线程池生命周期:
.setExecutorService(customExecutor, true)
- 若未设置自动关闭,需在应用停机时手动调用
customExecutor.shutdown(),避免线程泄漏。
内容的提问来源于stack exchange,提问作者user1429322
相关产品推荐
相关产品推荐

