我需要使用多个 LDAP 提供程序。如何检查 LDAP 服务器的可用性?

nik*_*kli 3 java authentication ldap

我们有多个 LDAP/域服务器。(例如LDAP://server1.com:389/DC=server1,DC=COM,LDAP://server2.com:389/DC=server2,DC=COM)我需要通过检查可用性来使用其中之一。

try {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "LDAP://server1.com:389/DC=server1,DC=COM");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, username);
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = new InitialDirContext(env);
} catch(NamingException ex) {
}
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以在 PROVIDER_URL 环境属性中使用多个 ldap 服务器 URL,如下所示:

Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");

// Specify list of space-separated URLs
env.put(Context.PROVIDER_URL, 
    "ldap://notthere:389/o=JNDITutorial " +
    "ldap://localhost:389/o=JNDITutorial " + 
    "ldap://remotehost/o=JNDITutorial " +
    "ldap://thirdhost:389/o=JNDITutorial");

// Create initial context
DirContext ctx = new InitialDirContext(env);

// See which server was used
System.out.println(ctx.getEnvironment().get(Context.PROVIDER_URL));

// do something useful with ctx
....
Run Code Online (Sandbox Code Playgroud)

无论哪个 URL 成功,都将在上下文中使用