基于ZooKeeper主机字符串的SolrCloud认证配置(SolrJ6.5.0)
Great question! When working with SolrCloud and SolrJ 6.5.0, the key is to configure the underlying HttpClient that CloudSolrClient uses to communicate with Solr nodes—since CloudSolrClient fetches Solr node URLs from ZooKeeper dynamically, you don't need to target individual core URLs directly. Here's how to set up authentication properly:
Step 1: Set Up Authentication Credentials
First, create a credentials provider to store your Solr username and password. This will be used by the HttpClient to automatically attach authentication details to every request sent to Solr nodes:
import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; // Initialize credentials provider CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( AuthScope.ANY, // Matches all Solr node URLs discovered from ZooKeeper new UsernamePasswordCredentials("your-solr-username", "your-solr-password") );
Step 2: Build an Authenticated HttpClient
Next, create an HttpClient instance that uses the credentials provider you just set up. This client will be used by CloudSolrClient for all its communication:
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; CloseableHttpClient authenticatedHttpClient = HttpClients.custom() .setDefaultCredentialsProvider(credentialsProvider) .build();
Step 3: Attach the Authenticated Client to CloudSolrClient
Finally, initialize your CloudSolrClient as you normally would, then assign the authenticated HttpClient to it:
import org.apache.solr.client.solrj.impl.CloudSolrClient; String zkConnectionStr = "zk-host1:2181,zk-host2:2181/solr"; // Your ZooKeeper connection string CloudSolrClient serverCloud = new CloudSolrClient.Builder() .withZkHost(zkConnectionStr) .build(); // Attach the authenticated HTTP client serverCloud.setHttpClient(authenticatedHttpClient);
Important Notes
- Server-Side Prerequisite: This setup assumes your SolrCloud cluster is already configured with an authentication plugin (like
BasicAuthPlugin). Without enabling authentication on the Solr server side, this client-side configuration won't have any effect. - HTTPS Consideration: If your Solr nodes use HTTPS, you'll need to add additional SSL configuration to the HttpClient (e.g., trusting the server's SSL certificate). You can extend the HttpClient builder with an
SSLContextto handle this. - AuthScope Flexibility: Using
AuthScope.ANYworks for most SolrCloud setups since all nodes will require the same credentials. If you have a more complex setup with different credentials per node, you can define specificAuthScopeinstances for each Solr node URL.
内容的提问来源于stack exchange,提问作者Zahra Aminolroaya

