目前,我正在使用Solrj库在SOLR云上使用SOLR基本身份验证功能。根据文档和我发现的唯一方法,代码看起来像这样 -
SolrRequest<QueryResponse> req = new QueryRequest(solrQuery);
req.setBasicAuthCredentials("admin", "foobar");
QueryResponse rsp = req.process(solrClient, liveStreamCollection);
documentList = rsp.getResults();
我想知道是否有办法避免每个请求setBasicAuthCredentials
,并且solrClient
每个会话只执行一次?
上述方法适用于SolrClient
和SolrCloudClient
(核心和集合)。为了避免为每个请求传递基本凭据,我尝试构建并使用这样的HttpClient
。
AuthScope authScope = new AuthScope("192.168.x.x", 8983);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "foobar");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(authScope, creds);
HttpClientBuilder builder = HttpClientBuilder.create();
builder.addInterceptorFirst(new PreemptiveAuthInterceptor());
builder.setDefaultCredentialsProvider(credsProvider);
CloseableHttpClient httpClient = builder.build();
solrClient = new HttpSolrClient("http://192.168.x.x:8983/solr/", httpClient);
PreemptiveAuthInterceptor
类:
static class PreemptiveAuthInterceptor implements HttpRequestInterceptor {
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
// If no auth scheme available yet, try to initialize it preemptively
if (authState.getAuthScheme() == null) {
CredentialsProvider credsProvider = (CredentialsProvider)
context.getAttribute(HttpClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if(creds == null){
}
authState.update(new BasicScheme(), creds);
}
}
}
这适用于单机Solr核心,但我不知道如何在Solr云中使用它(通过Zookeeper主机等)。有什么想法吗?
提前致谢!