java
  • timeout
  • blocking
  • nonblocking
  • 2016-02-25 290 views 3 likes 
    3
    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。有时它挂在最后一行。我不知道为什么。它有时在性能测试中重现。在Ldap搜索设置方法超时

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

    P.S.

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

    回答

    3

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

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

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

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

    这将导致LDAP服务提供商中止读取尝试,如果服务器在1秒内没有响应。如果超时达到,将会播放NamingException


    注意从this Stack Overflow post,您不能使用该方法SearchControls.setTimeLimit这个,因为这个paramater不适用于读取超时。

    +0

    @RealSkeptic和Tunaki请澄清差异 – gstackoverflow

    +0

    @gstackoverflow这可能不完全正确(我不确定所有的贪婪细节),但'setTimeLimit'不用于搜索操作(我不确定为什么) – Tunaki

    +0

    NamingException是常见的ldap异常。我没有检查,但我认为TimeLimitExceededException将被抛出 – gstackoverflow

    0

    您的SearchControls最有可能有一个方法来设置超时。你能检查一下吗?你应该可以做ctrls.setTimeLimit(ms);

    +0

    http://stackoverflow.com/questions/16926012/does-searchcontrols-settimelimit-handle-read-timeout – Tunaki

    相关问题