设置 Ldap 搜索的方法超时

gst*_*low 4 java timeout nonblocking blocking

private Authentication authenticateUserPassword(UsernamePasswordAuthenticationToken token) throws NamingException {
    Object login = login(token);
    LOGGER.debug("Starting authentication login='{}'", login);
    Object password = token.getCredentials();

    LdapContext ctx = createLdapCtx(login, password);
    SearchControls ctrls = createSearchControls();
    String filter = String.format(this.filter, login);

    NamingEnumeration<SearchResult> ne = ctx.search(dn, filter, ctrls);
    ....
Run Code Online (Sandbox Code Playgroud)

我有以下方法来登录用户。这取决于 LDAP。有时它挂在最后一排。我不知道为什么。它有时会在性能测试中重现。

有没有办法等待一段时间,如果方法没有响应 - 返回一些预定义的值?

聚苯乙烯

private LdapContext createLdapCtx(Object login, Object password) throws NamingException {
    Hashtable<String, String> props = new Hashtable<String, String>();
    props.put(Context.INITIAL_CONTEXT_FACTORY, factory);
    props.put(Context.PROVIDER_URL, url);
    props.put(Context.SECURITY_AUTHENTICATION, "simple");
    props.put(Context.SECURITY_PRINCIPAL, String.format(domain, login));
    props.put(Context.SECURITY_CREDENTIALS, password.toString());

    return new InitialLdapContext(props, null);
}
Run Code Online (Sandbox Code Playgroud)

Tun*_*aki 6

您可以为所有 Ldap 操作设置超时

新的环境属性:com.sun.jndi.ldap.read.timeout可用于指定 LDAP 操作的读取超时。此属性的值是整数的字符串表示形式,表示 LDAP 操作的读取超时(以毫秒为单位)。

因此,您只需更新createLdapCtx方法即可将该环境变量指定为您选择的值:

props.put("com.sun.jndi.ldap.read.timeout", "1000"); // 1 second of timeout here
Run Code Online (Sandbox Code Playgroud)

如果服务器在 1 秒内没有响应,这将导致 LDAP 服务提供商中止读取尝试。如果超时,aNamingException将被丢弃。


请注意,从这篇 Stack Overflow 帖子中,您不能使用SearchControls.setTimeLimit该方法,因为此参数不适用于读取超时。