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