java - 在 Ldap 搜索上设置方法超时

标签 java timeout blocking nonblocking

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);
    ....

我有以下登录用户的方法。这取决于 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);
}

最佳答案

你可以设置一个time-out for all Ldap operations :

The new environment property: com.sun.jndi.ldap.read.timeout can be used to specify the read timeout for an LDAP operation. The value of this property is the string representation of an integer representing the read timeout in milliseconds for LDAP operations.

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

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

如果服务器在 1 秒内没有响应,这将导致 LDAP 服务提供者中止读取尝试。如果达到超时,将抛出一个 NamingException


请注意,来自 this Stack Overflow post ,您不能为此使用方法 SearchControls.setTimeLimit,因为此参数不适用于读取超时。

关于java - 在 Ldap 搜索上设置方法超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35637476/

相关文章:

python - "blocking"这个词在编程中是什么意思?

java - 杀死正在等待套接字输出的线程

java - 你如何测试一个 double 值是否等于 NaN?

javascript - AngularJS( CoffeeScript ): $interval only runs once

android - android应用开发中如何屏蔽手机号码的来电和短信接收?

用于大文件解析的 Php 脚本在中间中断

MySQL 连接超时问题 - 使用 Hibernate 和 ORM 的 Tomcat 上的 Grails 应用程序

java - 微调器文本不显示默认值,也不显示所选值

java - AOP+同步

java - 在IntelliJ中使用protobufs构建gradle时出错