Skip to content

Commit

Permalink
up hc
Browse files Browse the repository at this point in the history
  • Loading branch information
youfanx committed Jun 21, 2024
1 parent f29f873 commit c93c61a
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 40 deletions.
3 changes: 3 additions & 0 deletions rxlib/src/main/java/org/rx/core/RxConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public interface ConfigNames {
String NET_REACTOR_THREAD_AMOUNT = "app.net.reactorThreadAmount";
String NET_ENABLE_LOG = "app.net.enableLog";
String NET_CONNECT_TIMEOUT_MILLIS = "app.net.connectTimeoutMillis";
String NET_READ_WRITE_TIMEOUT_MILLIS = "app.net.readWriteTimeoutMillis";
String NET_POOL_MAX_SIZE = "app.net.poolMaxSize";
String NET_POOL_KEEP_ALIVE_SECONDS = "app.net.poolKeepAliveSeconds";
String NET_USER_AGENT = "app.net.userAgent";
Expand Down Expand Up @@ -142,6 +143,7 @@ public static class NetConfig {
int reactorThreadAmount;
boolean enableLog;
int connectTimeoutMillis;
int readWriteTimeoutMillis;
int poolMaxSize;
int poolKeepAliveSeconds;
String userAgent;
Expand Down Expand Up @@ -249,6 +251,7 @@ public void refreshFromSystemProperty() {
net.reactorThreadAmount = SystemPropertyUtil.getInt(ConfigNames.NET_REACTOR_THREAD_AMOUNT, net.reactorThreadAmount);
net.enableLog = SystemPropertyUtil.getBoolean(ConfigNames.NET_ENABLE_LOG, net.enableLog);
net.connectTimeoutMillis = SystemPropertyUtil.getInt(ConfigNames.NET_CONNECT_TIMEOUT_MILLIS, net.connectTimeoutMillis);
net.readWriteTimeoutMillis = SystemPropertyUtil.getInt(ConfigNames.NET_READ_WRITE_TIMEOUT_MILLIS, net.readWriteTimeoutMillis);
net.poolMaxSize = SystemPropertyUtil.getInt(ConfigNames.NET_POOL_MAX_SIZE, net.poolMaxSize);
if (net.poolMaxSize <= 0) {
net.poolMaxSize = Math.max(10, Constants.CPU_THREADS * 2);
Expand Down
81 changes: 50 additions & 31 deletions rxlib/src/main/java/org/rx/net/http/HttpClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ public String toString() {

public static final CookieContainer COOKIES = new CookieContainer();
static final ConnectionPool POOL = new ConnectionPool(RxConfig.INSTANCE.getNet().getPoolMaxSize(), RxConfig.INSTANCE.getNet().getPoolKeepAliveSeconds(), TimeUnit.SECONDS);
static final MediaType FORM_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"), JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
static final MediaType FORM_TYPE = MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
static final X509TrustManager TRUST_MANAGER = new X509TrustManager() {
final X509Certificate[] empty = new X509Certificate[0];

Expand Down Expand Up @@ -376,15 +376,15 @@ public static void saveRawCookie(@NonNull String url, @NonNull String cookie) {
}

@SneakyThrows
static OkHttpClient createClient(long timeoutMillis, boolean enableCookie, Proxy proxy) {
static OkHttpClient createClient(long connectTimeoutMillis, long readWriteTimeoutMillis, boolean enableCookie, Proxy proxy) {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{TRUST_MANAGER}, new SecureRandom());
Authenticator authenticator = proxy instanceof AuthenticProxy ? ((AuthenticProxy) proxy).getAuthenticator() : Authenticator.NONE;
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), TRUST_MANAGER).hostnameVerifier((s, sslSession) -> true)
.connectionPool(POOL).retryOnConnectionFailure(true) //unexpected end of stream
.connectTimeout(timeoutMillis, TimeUnit.MILLISECONDS)
.readTimeout(timeoutMillis, TimeUnit.MILLISECONDS).writeTimeout(timeoutMillis, TimeUnit.MILLISECONDS)
.connectTimeout(connectTimeoutMillis, TimeUnit.MILLISECONDS)
.readTimeout(readWriteTimeoutMillis, TimeUnit.MILLISECONDS).writeTimeout(readWriteTimeoutMillis, TimeUnit.MILLISECONDS)
.proxy(proxy).proxyAuthenticator(authenticator);
if (enableCookie) {
builder.cookieJar(COOKIES);
Expand All @@ -393,31 +393,55 @@ static OkHttpClient createClient(long timeoutMillis, boolean enableCookie, Proxy
}
//endregion

@Setter
boolean enableLog = RxConfig.INSTANCE.getNet().isEnableLog();
@Setter
boolean cachingStream = true;
long timeoutMillis;
boolean enableCookie;
static byte CACHING_STREAM_FLAG = 1, ENABLE_COOKIE_FLAG = 1 << 1, ENABLE_LOG_FLAG = 1 << 2;
//1 cachingStream, 2 enableCookie, 4 enableLog
byte featureFlags = CACHING_STREAM_FLAG;
long connectTimeoutMillis, readWriteTimeoutMillis;
AuthenticProxy proxy;
//Not thread safe
OkHttpClient client;
HttpHeaders reqHeaders;
ResponseContent resContent;

public synchronized void setTimeoutMillis(long timeoutMillis) {
this.timeoutMillis = timeoutMillis;
public HttpClient withFeatures(boolean enableCookie, boolean enableLog) {
return withFeatures(enableCookie, enableLog);
}

public synchronized HttpClient withFeatures(boolean enableCookie, boolean enableLog, boolean cachingStream) {
if (enableLog) {
featureFlags |= ENABLE_LOG_FLAG;
} else {
featureFlags &= ~ENABLE_LOG_FLAG;
}
if (enableCookie) {
featureFlags |= ENABLE_COOKIE_FLAG;
} else {
featureFlags &= ~ENABLE_COOKIE_FLAG;
}
if (cachingStream) {
featureFlags |= CACHING_STREAM_FLAG;
} else {
featureFlags &= ~CACHING_STREAM_FLAG;
}
client = null;
return this;
}

public HttpClient withTimeoutMillis(long timeoutMillis) {
return withTimeoutMillis(timeoutMillis, timeoutMillis);
}

public synchronized void setEnableCookie(boolean enableCookie) {
this.enableCookie = enableCookie;
public synchronized HttpClient withTimeoutMillis(long connectTimeoutMillis, long readWriteTimeoutMillis) {
this.connectTimeoutMillis = connectTimeoutMillis;
this.readWriteTimeoutMillis = readWriteTimeoutMillis;
client = null;
return this;
}

public synchronized void setProxy(AuthenticProxy proxy) {
public synchronized HttpClient withProxy(AuthenticProxy proxy) {
this.proxy = proxy;
client = null;
return this;
}

public HttpClient withUserAgent() {
Expand Down Expand Up @@ -445,21 +469,14 @@ public HttpHeaders requestHeaders(boolean readOnly) {
}

public HttpClient() {
this(RxConfig.INSTANCE.getNet().getConnectTimeoutMillis());
}

public HttpClient(long timeoutMillis) {
this(timeoutMillis, false);
}

public HttpClient(long timeoutMillis, boolean enableCookie) {
this.timeoutMillis = timeoutMillis;
this.enableCookie = enableCookie;
RxConfig.NetConfig conf = RxConfig.INSTANCE.getNet();
withFeatures(false, conf.isEnableLog());
withTimeoutMillis(conf.getConnectTimeoutMillis(), conf.getReadWriteTimeoutMillis());
}

OkHttpClient getClient() {
if (client == null) {
client = createClient(timeoutMillis, enableCookie, proxy);
client = createClient(connectTimeoutMillis, readWriteTimeoutMillis, (featureFlags & ENABLE_COOKIE_FLAG) == ENABLE_COOKIE_FLAG, proxy);
}
return client;
}
Expand All @@ -473,8 +490,10 @@ Request.Builder createRequest(String url) {
}

@SneakyThrows
private synchronized ResponseContent invoke(String url, HttpMethod method, RequestContent content) {
ProceedEventArgs args = new ProceedEventArgs(this.getClass(), new Object[]{method.toString(), content.toString()}, false);
synchronized ResponseContent invoke(String url, HttpMethod method, RequestContent content) {
ProceedEventArgs args = new ProceedEventArgs(this.getClass(),
new Object[]{method.toString(), content instanceof JsonContent ? ((JsonContent) content).json : content.toString()},
false);
try {
Request.Builder request = createRequest(url);
RequestBody requestBody = content.toBody();
Expand All @@ -498,14 +517,14 @@ private synchronized ResponseContent invoke(String url, HttpMethod method, Reque
}
return resContent = args.proceed(() -> {
ResponseContent rc = new ResponseContent(getClient().newCall(request.build()).execute());
rc.cachingStream = cachingStream;
rc.cachingStream = (featureFlags & CACHING_STREAM_FLAG) == CACHING_STREAM_FLAG;
return rc;
});
} catch (Throwable e) {
args.setError(e);
throw e;
} finally {
if (enableLog) {
if ((featureFlags & ENABLE_LOG_FLAG) == ENABLE_LOG_FLAG) {
logHttp(args, url);
}
}
Expand Down Expand Up @@ -628,7 +647,7 @@ public RequestBody toBody() {
// boolean isGet = Strings.equalsIgnoreCase(servletRequest.getMethod(), HttpMethod.GET.name());
// ResponseContent resContent = new ResponseContent(getClient().newCall(createRequest(forwardUrl).method(servletRequest.getMethod(), isGet ? null : reqContent.toBody()).build()).execute());
ResponseContent resContent = new ResponseContent(getClient().newCall(createRequest(forwardUrl).method(servletRequest.getMethod(), reqContent.toBody()).build()).execute());
resContent.cachingStream = cachingStream;
resContent.cachingStream = (featureFlags & CACHING_STREAM_FLAG) == CACHING_STREAM_FLAG;
servletResponse.setStatus(resContent.response.code());
for (Pair<? extends String, ? extends String> header : resContent.responseHeaders()) {
servletResponse.setHeader(header.getFirst(), header.getSecond());
Expand Down
6 changes: 2 additions & 4 deletions rxlib/src/main/java/org/rx/net/support/ComboIPSearcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public ComboIPSearcher() {

@Override
public String currentIp() {
return Tasks.randomRetry(() -> new HttpClient(TIMEOUT_SECONDS).get("https://api.ipify.org").toString(),
return Tasks.randomRetry(() -> new HttpClient().withTimeoutMillis(TIMEOUT_SECONDS).get("https://api.ipify.org").toString(),
() -> searchCurrent().getIp());
}

Expand Down Expand Up @@ -177,9 +177,7 @@ IPAddress ipInfo(String ip) {
}

private JSONObject getJson(String url, PredicateFunc<JSONObject> check) {
HttpClient client = new HttpClient(TIMEOUT_SECONDS);
client.setEnableLog(true);
String text = client.get(url).toString();
String text = new HttpClient().withFeatures(false, true).withTimeoutMillis(TIMEOUT_SECONDS).get(url).toString();
if (Strings.isEmpty(text)) {
throw new InvalidException("Empty response from {}", url);
}
Expand Down
4 changes: 1 addition & 3 deletions rxlib/src/main/java/org/rx/net/support/IPSearcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ static String godaddyDns(String ssoKey, String domain, String name) {

static String godaddyDns(String ssoKey, String domain, String name, String ip, AuthenticProxy proxy) {
String u = String.format("https://api.godaddy.com/v1/domains/%s/records/A/%s", domain, name);
HttpClient c = new HttpClient();
c.setEnableLog(true);
c.setProxy(proxy);
HttpClient c = new HttpClient().withFeatures(false, true).withProxy(proxy);
c.requestHeaders().add("Authorization", "sso-key " + ssoKey);
return c.putJson(u, String.format("[\n" +
" {\n" +
Expand Down
1 change: 1 addition & 0 deletions rxlib/src/main/resources/rx.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ app:
reactorThreadAmount: 0
enableLog: false
connectTimeoutMillis: 15000
readWriteTimeoutMillis: 60000
poolMaxSize: 0
poolKeepAliveSeconds: 120
userAgent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36 QBCore/4.0.1301.400 QQBrowser/9.0.2524.400 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2875.116 Safari/537.36 NetType/WIFI MicroMessenger/7.0.5 WindowsWechat
Expand Down
3 changes: 1 addition & 2 deletions rxlib/src/test/java/org/rx/net/TestSocks.java
Original file line number Diff line number Diff line change
Expand Up @@ -959,8 +959,7 @@ public void httpServer() {
});

RxConfig.INSTANCE.setLogStrategy(LogStrategy.ALWAYS);
HttpClient client = new HttpClient();
client.setEnableLog(true);
HttpClient client = new HttpClient().withFeatures(false, true);
assert hbody.equals(client.post(HttpClient.buildUrl("https://127.0.0.1:8081/api", qs), f, fi).toString());

String resJson = client.postJson("https://127.0.0.1:8081/json", j).toString();
Expand Down
Loading

0 comments on commit c93c61a

Please sign in to comment.