Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- BasicAuthSolrClientCache bs = new BasicAuthSolrClientCache("solr", "SolrRocks");
- CloudSolrClient solrCloudClient = bs.getCloudSolrClient(zkHost);
- solrCloudClient.setDefaultCollection("sample");
- SolrInputDocument doc = new SolrInputDocument();
- doc.addField("cat", "book");
- doc.addField("id", "book-1");
- doc.addField("name", "The Legend of the Hobbit part 1");
- solrCloudClient.add(doc);
- solrCloudClient.commit();
- solrCloudClient.close();
- public class BasicAuthSolrClientCache extends SolrClientCache {
- private static final Logger log =
- LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- private final Map<String, SolrClient> solrClients = new HashMap<>();
- private final String username;
- private final String password;
- public BasicAuthSolrClientCache(String username, String password) {
- this.username = username;
- this.password = password;
- }
- @Override
- public synchronized CloudSolrClient getCloudSolrClient(String zkHost) {
- CloudSolrClient client;
- if (solrClients.containsKey(zkHost)) {
- client = (CloudSolrClient) solrClients.get(zkHost);
- } else {
- client = new CloudSolrClient.Builder()
- .withZkHost(zkHost)
- .withHttpClient(getHttpClient())
- .build();
- client.connect();
- solrClients.put(zkHost, client);
- }
- return client;
- @Override
- public synchronized HttpSolrClient getHttpSolrClient(String host) {
- HttpSolrClient client;
- if (solrClients.containsKey(host)) {
- client = (HttpSolrClient) solrClients.get(host);
- } else {
- client = new HttpSolrClient.Builder(host)
- .withHttpClient(getHttpClient())
- .build();
- solrClients.put(host, client);
- }
- return client;
- }
- @Override
- public synchronized void close() {
- for(Map.Entry<String, SolrClient> entry : solrClients.entrySet()) {
- try {
- entry.getValue().close();
- } catch (IOException e) {
- log.error("Error closing SolrClient for " + entry.getKey(), e);
- }
- }
- solrClients.clear();
- }
- private HttpClient getHttpClient() {
- CredentialsProvider provider = new BasicCredentialsProvider();
- UsernamePasswordCredentials credentials = new
- UsernamePasswordCredentials(this.username, this.password);
- provider.setCredentials(AuthScope.ANY, credentials);
- return
- HttpClientBuilder.create().setDefaultCredentialsProvider(provider).
- build();
- }
- }
Add Comment
Please, Sign In to add comment