是否可以提高用于发出 HTTPS 请求的 SSLSocketFactory/SSLContext 初始设置的性能?
在我测试的几台机器上,第一个HTTPS 请求需要 >600 毫秒,这对于我们的用例来说太高了。
long start = System.currentTimeMillis();
// System.out.println("creating factory...");
// SocketFactory factory = SSLSocketFactory.getDefault();
// System.out.println("factory created " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
URL url = new URL("https://example.com");
System.out.println("url created " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
System.out.println("connection opened " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
assert connection.getResponseCode() == 200;
System.out.println("response code retrieved " + (System.currentTimeMillis() - start));
定时:
url created 0
connection opened 656
response code retrieved 0
正如我发现的那样,大部分时间实际上并没有花在连接本身(握手、数据传输等)上,而是花在了SSLSocketFactory
.
取消注释工厂代码后:
creating factory...
factory created 683
url created 1
connection opened 3
response code retrieved 0
我也尝试过直接创建 SSLContext ( SSLContext sc = SSLContext.getInstance("TLSv1.2"); sc.init(...); ...
),但性能几乎相同。
问:上下文设置如此昂贵有什么特别的原因吗?是否可以加快速度和/或使用一些不会受到相同初始成本影响的替代库?