|
| 1 | +package io.github.easy4j.opencode; |
| 2 | + |
| 3 | +import okhttp3.ConnectionPool; |
| 4 | +import okhttp3.Dispatcher; |
| 5 | +import okhttp3.OkHttpClient; |
| 6 | + |
| 7 | +import java.util.Objects; |
| 8 | +import java.util.concurrent.TimeUnit; |
| 9 | + |
| 10 | +/** |
| 11 | + * OpenCode 独立运行时使用的 OkHttpClient 工厂。 |
| 12 | + * |
| 13 | + * <p>Spring 容器已经提供外部 {@link OkHttpClient} 时应使用注入构造器,本工厂不会参与。</p> |
| 14 | + */ |
| 15 | +public final class OpenCodeOkHttpClientFactory { |
| 16 | + |
| 17 | + private OpenCodeOkHttpClientFactory() { |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * 根据 OpenCode HTTP 配置创建客户端。 |
| 22 | + * |
| 23 | + * @param config HTTP 配置 |
| 24 | + * @return SDK 自主管理的 OkHttpClient |
| 25 | + */ |
| 26 | + public static OkHttpClient create(OpenCodeHttpClientConfig config) { |
| 27 | + Objects.requireNonNull(config, "config"); |
| 28 | + Dispatcher dispatcher = new Dispatcher(); |
| 29 | + dispatcher.setMaxRequests(Math.max(1, config.getMaxRequests())); |
| 30 | + dispatcher.setMaxRequestsPerHost(Math.max(1, config.getMaxRequestsPerHost())); |
| 31 | + ConnectionPool connectionPool = new ConnectionPool( |
| 32 | + Math.max(1, config.getMaxIdleConnections()), |
| 33 | + Math.max(1L, config.getKeepAliveDurationMillis()), |
| 34 | + TimeUnit.MILLISECONDS); |
| 35 | + OkHttpClient.Builder builder = new OkHttpClient.Builder() |
| 36 | + .dispatcher(dispatcher) |
| 37 | + .connectionPool(connectionPool) |
| 38 | + .connectTimeout(Math.max(1, config.getConnectTimeoutMillis()), TimeUnit.MILLISECONDS) |
| 39 | + .readTimeout(Math.max(0, config.getReadTimeoutMillis()), TimeUnit.MILLISECONDS) |
| 40 | + .writeTimeout(Math.max(1, config.getWriteTimeoutMillis()), TimeUnit.MILLISECONDS) |
| 41 | + .callTimeout(Math.max(0, config.getCallTimeoutMillis()), TimeUnit.MILLISECONDS) |
| 42 | + .retryOnConnectionFailure(config.isRetryOnConnectionFailure()); |
| 43 | + if (!config.isVerifySsl()) { |
| 44 | + builder.hostnameVerifier((hostname, session) -> true); |
| 45 | + } |
| 46 | + return builder.build(); |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * 释放 SDK 自建客户端资源。 |
| 51 | + * |
| 52 | + * @param client SDK 自建客户端 |
| 53 | + */ |
| 54 | + public static void shutdown(OkHttpClient client) { |
| 55 | + if (Objects.isNull(client)) { |
| 56 | + return; |
| 57 | + } |
| 58 | + client.dispatcher().cancelAll(); |
| 59 | + client.connectionPool().evictAll(); |
| 60 | + client.dispatcher().executorService().shutdown(); |
| 61 | + } |
| 62 | +} |
0 commit comments