Java 11中AuthCacheValue与AuthCacheImpl的替代方案是什么
JDK11中AuthCacheValue与AuthCacheImpl的替代方案
官方公开API替代
JDK9引入模块化机制后,所有sun.*前缀的内部非公开API都被默认隐藏,不对外暴露,官方也从未推荐开发者依赖这类内部类。针对原有的HTTP认证缓存能力,官方提供了两个公开可依赖的替代路径:
- 针对传统
HttpURLConnection场景:直接使用java.net.Authenticator类自带的全局认证缓存能力即可,JDK默认已经开启该缓存,你可以通过以下系统属性调整默认缓存行为:- 调整全局缓存最大条目数:
-Dhttp.auth.cache_size=20,默认值为20 - 关闭特定认证类型的缓存:比如Digest认证可以设置
-Dhttp.auth.digest.validateServer=true,TLS会话认证可以设置-Dhttp.auth.tls.serversession.cacheSize=0
- 调整全局缓存最大条目数:
- 针对JDK11新增的标准化
HttpClient场景:构建HttpClient实例时通过authenticator()方法传入自定义的Authenticator实现即可,HttpClient会自动处理认证凭证的缓存逻辑,不需要额外手动维护。
自定义认证缓存实现
如果官方默认的缓存逻辑不满足业务需求(比如需要自定义过期规则、手动失效指定凭证),可以基于公开API自行实现轻量认证缓存,完全替代原有AuthCacheImpl的能力,示例代码如下:
import java.net.Authenticator; import java.net.PasswordAuthentication; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class CustomAuthCache { // 缓存Key格式:请求主机:请求端口:认证方案 private static final ConcurrentMap<String, PasswordAuthentication> CACHE = new ConcurrentHashMap<>(); static { // 注册全局自定义认证器 Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { String cacheKey = String.format("%s:%d:%s", getRequestingHost(), getRequestingPort(), getRequestingScheme()); // 优先从缓存取凭证 PasswordAuthentication cred = CACHE.get(cacheKey); if (cred != null) { return cred; } // 此处替换为实际的凭证获取逻辑,比如读取配置、调用凭证服务等 cred = new PasswordAuthentication("your_username", "your_password".toCharArray()); // 凭证有效则写入缓存 CACHE.put(cacheKey, cred); return cred; } }); } /** * 手动清除指定服务的失效凭证 */ public static void invalidate(String host, int port, String scheme) { String cacheKey = String.format("%s:%d:%s", host, port, scheme); CACHE.remove(cacheKey); } }
该实现完全基于JDK公开标准API,兼容JDK8及以上所有版本,不受内部API变更影响,还可以根据业务需要扩展缓存过期、批量清空等能力。
内容的提问来源于stack exchange,提问作者user2951756
相关产品推荐
相关产品推荐

