使用solrj连接到带凭证的solr服务器

时间:2013-09-17 10:26:50

标签: java solr solrj

我正在尝试使用以下代码连接到solr服务器:

SolrServer solr = new HttpSolrServer("http://localhost:8080/solr-all");
SolrQuery query = new SolrQuery();

query.setQuery("*:*");
query.setRows(10);
query.setStart(0);

QueryResponse response = solr.query(query);
System.out.println(response);

但是我收到了这个错误:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException: Server at http://localhost:8080/solr-all returned non ok status:401, message:Unauthorized

我真的不知道如何设置用户名和密码,我在网上发现了很多使用htttpclient的exaples,但没有一个能为我工作。

3 个答案:

答案 0 :(得分:1)

设置凭据:

httpclient.getCredentialsProvider().setCredentials(
                    AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
solrServer = new HttpSolrServer(solrUrl, httpclient);//with credentials

检查类似的讨论:

  

Solr 4 with basic authentication

答案 1 :(得分:0)

SolrConfig:

@Configuration
public class SolrConfig {

    @Value("${solr.http.url}")
    private String solrUrl;

    @Value("${solr.http.username}")
    private String solrUser;

    @Value("${solr.http.password}")
    private String solrPassword;

    @Value("${solr.http.pool.maxTotal}")
    private int poolMaxTotal;

    @Value("${solr.http.pool.maxPerRoute}")
    private int pollMaxPerRoute;

    @Bean
    public SolrClient solrClient() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(poolMaxTotal);
        connectionManager.setDefaultMaxPerRoute(pollMaxPerRoute);

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(solrUser, solrPassword));

        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .addInterceptorFirst(new PreemptiveAuthInterceptor())
                .setConnectionManager(connectionManager)
                .setDefaultCredentialsProvider(credentialsProvider)
                .build();

        return new HttpSolrClient.Builder(solrUrl).withHttpClient(httpClient).build();
    }


}

PreemptiveAuthInterceptor:

public class PreemptiveAuthInterceptor implements HttpRequestInterceptor {

    public void process(final HttpRequest request, final HttpContext context)
            throws HttpException {
        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 credentialsProvider = (CredentialsProvider) context
                    .getAttribute(HttpClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context
                    .getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            Credentials credentials = credentialsProvider.getCredentials(new AuthScope(
                    targetHost.getHostName(), targetHost.getPort()));
            if (credentials == null) {
                throw new HttpException(
                        "No credentials for preemptive authentication");
            }
            authState.update(new BasicScheme(), credentials);
        }

    }

}

SolrController:

@RestController
public class SolrController {

    private final SolrClient solrClient;
    private final Gson gson;

    @Autowired
    public SolrController(SolrClient solrClient, Gson gson) {
        this.solrClient = solrClient;
        this.gson = gson;
    }

    @GetMapping("/search")
    SolrDocumentList search(@RequestParam("q") String q) {
        SolrQuery query = new SolrQuery();
        query.set("q", q);

        QueryRequest queryRequest = new QueryRequest(query);
        QueryResponse response = queryRequest.process(solrClient);
        return response.getResults();
    }

    @PutMapping("/add")
    public void addIndex(HttpEntity<String> httpEntity) {
        Type type = new TypeToken<Map<String, Object>>(){}.getType();
        Map<String, Object> map = gson.fromJson(httpEntity.getBody(), type);
        if (isNull(map)) return;
        SolrInputDocument doc = new SolrInputDocument();
        for (var entry : map.entrySet()) {
            doc.addField(entry.getKey(), entry.getValue());
        }

        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.add(doc);
        solrClient.request(updateRequest);
    }

}

答案 2 :(得分:-2)

您能否在运行时检查Slf4j?

 Failed to load class "org.slf4j.impl.StaticLoggerBinder"

表示您的代码在运行时需要此类。