1

我正在尝试使用以下代码连接到 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但没有一个对我有用。

4

3 回答 3

1

要设置凭据:

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

检查类似的讨论:

具有基本身份验证的 Solr 4

于 2013-09-17T10:33:21.527 回答
0

Solr配置:

@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);
        }

    }

}

Solr控制器:

@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);
    }

}
于 2021-08-03T11:22:27.730 回答
-2

您能否检查一下 Slf4j 在运行时是否可用?

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

意味着您的代码在运行时需要此类。

于 2013-09-17T10:30:26.047 回答