java 缓存 cachedKeyStore cachedSSLContext ?
分析只缓存 SSLContext
的情况优点:从功能角度来说,缓存SSLContext
可以直接用于构建HttpClient
。因为SSLContext
已经包含了信任管理(通过TrustManager
初始化)等相关信息,后续在循环调用时,直接使用缓存的SSLContext
来构建HttpClient
可以避免重复的KeyStore
加载、TrustManagerFactory
初始化等操作,能够提高性能。例如:
if (!isInitialized) { KeyStore keyStore = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream(SystemVar.tomcatJKS); keyStore.load(fis, SystemVar.tomcatJKSPassword.toCharArray()); fis.close(); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, new java.security.SecureRandom()); // 只缓存SSLContext cachedSSLContext = sslContext; isInitialized = true; } else { HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .sslContext(cachedSSLContext) .build(); java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder() .uri(URI.create(urlStr)) .timeout(java.time.Duration.ofSeconds(10)) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); jsonString = response.body(); }
潜在问题:
分析只缓存 KeyStore
的情况优点:KeyStore
是存储证书和密钥的仓库,缓存它可以在后续需要时灵活地进行各种操作。例如,如果要更新SSLContext
的信任配置(如添加新的信任证书或者更新证书密码等操作),有缓存的KeyStore
可以方便地重新初始化TrustManagerFactory
和SSLContext
。示例如下:
if (!isInitialized) { KeyStore keyStore = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream(SystemVar.tomcatJKS); keyStore.load(fis, SystemVar.tomcatJKSPassword.toCharArray()); fis.close(); // 只缓存KeyStore cachedKeyStore = keyStore; isInitialized = true; } else { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(cachedKeyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, new java.security.SecureRandom()); HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .sslContext(sslContext) .build(); java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder() .uri(URI.create(urlStr)) .timeout(java.time.Duration.ofSeconds(10)) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); jsonString = response.body(); }
结论