且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Solr的4基本身份验证

更新时间:2023-12-01 08:16:10

我实现部分文档更新时有同样的问题。我通过实现preemptiveAuthInterceptor解决了这个问题。见下文code

i had the same problem when implementing partial documents update. i solved the problem by implementing PreemptiveAuthInterceptor. see below code

PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager(
                        SchemeRegistryFactory.createDefault());
                cxMgr.setMaxTotal(100);
                cxMgr.setDefaultMaxPerRoute(20);

                DefaultHttpClient httpclient = new DefaultHttpClient(cxMgr);
                httpclient.addRequestInterceptor(
                        new PreemptiveAuthInterceptor(), 0);
                httpclient.getCredentialsProvider().setCredentials(
                        AuthScope.ANY,
                        new UsernamePasswordCredentials(solrDto.getUsername(),
                                solrDto.getPassword()));

                HttpSolrServer solrServerInstance = new HttpSolrServer(solrDto.getUrl(),
                        httpclient);
                solrServerInstance.setRequestWriter(new BinaryRequestWriter());
                solrServerInstance.setAllowCompression(true);

您还需要:

    private class PreemptiveAuthInterceptor implements HttpRequestInterceptor {

            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                AuthState authState = (AuthState) context
                        .getAttribute(ClientContext.TARGET_AUTH_STATE);

                // If no auth scheme avaialble yet, try to initialize it
                // preemptively
                if (authState.getAuthScheme() == null) {
                    CredentialsProvider credsProvider = (CredentialsProvider) context
                            .getAttribute(ClientContext.CREDS_PROVIDER);
                    HttpHost targetHost = (HttpHost) context
                            .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                    Credentials creds = credsProvider.getCredentials(new AuthScope(
                            targetHost.getHostName(), targetHost.getPort()));
                    if (creds == null)
                        throw new HttpException(
                                "No credentials for preemptive authentication");
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }

            }

        }