Guest User

Untitled

a guest
Oct 28th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. BasicAuthSolrClientCache bs = new BasicAuthSolrClientCache("solr", "SolrRocks");
  2.  
  3. CloudSolrClient solrCloudClient = bs.getCloudSolrClient(zkHost);
  4. solrCloudClient.setDefaultCollection("sample");
  5.  
  6. SolrInputDocument doc = new SolrInputDocument();
  7. doc.addField("cat", "book");
  8. doc.addField("id", "book-1");
  9. doc.addField("name", "The Legend of the Hobbit part 1");
  10. solrCloudClient.add(doc);
  11. solrCloudClient.commit();
  12. solrCloudClient.close();
  13.  
  14. public class BasicAuthSolrClientCache extends SolrClientCache {
  15.  
  16. private static final Logger log =
  17. LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
  18.  
  19. private final Map<String, SolrClient> solrClients = new HashMap<>();
  20. private final String username;
  21. private final String password;
  22.  
  23. public BasicAuthSolrClientCache(String username, String password) {
  24. this.username = username;
  25. this.password = password;
  26. }
  27.  
  28. @Override
  29. public synchronized CloudSolrClient getCloudSolrClient(String zkHost) {
  30. CloudSolrClient client;
  31. if (solrClients.containsKey(zkHost)) {
  32. client = (CloudSolrClient) solrClients.get(zkHost);
  33. } else {
  34. client = new CloudSolrClient.Builder()
  35. .withZkHost(zkHost)
  36. .withHttpClient(getHttpClient())
  37. .build();
  38. client.connect();
  39. solrClients.put(zkHost, client);
  40. }
  41.  
  42. return client;
  43.  
  44. @Override
  45. public synchronized HttpSolrClient getHttpSolrClient(String host) {
  46. HttpSolrClient client;
  47. if (solrClients.containsKey(host)) {
  48. client = (HttpSolrClient) solrClients.get(host);
  49. } else {
  50. client = new HttpSolrClient.Builder(host)
  51. .withHttpClient(getHttpClient())
  52. .build();
  53. solrClients.put(host, client);
  54. }
  55. return client;
  56. }
  57.  
  58. @Override
  59. public synchronized void close() {
  60. for(Map.Entry<String, SolrClient> entry : solrClients.entrySet()) {
  61. try {
  62. entry.getValue().close();
  63. } catch (IOException e) {
  64. log.error("Error closing SolrClient for " + entry.getKey(), e);
  65. }
  66. }
  67. solrClients.clear();
  68. }
  69.  
  70. private HttpClient getHttpClient() {
  71. CredentialsProvider provider = new BasicCredentialsProvider();
  72. UsernamePasswordCredentials credentials = new
  73. UsernamePasswordCredentials(this.username, this.password);
  74. provider.setCredentials(AuthScope.ANY, credentials);
  75. return
  76.  
  77.  
  78. HttpClientBuilder.create().setDefaultCredentialsProvider(provider).
  79. build();
  80. }
  81. }
Add Comment
Please, Sign In to add comment