backup-s-server

public class SolrClientFactory {

private static Map<String, SolrClient> SERVERS = new ConcurrentHashMap<String, SolrClient>();

/**

* Get a solrClient by a specified core/collection name

* @param coreName

* @return a SolrClient

*/

public static SolrClient getSolrClient(String coreName)

{

if(StringUtils.isBlank(coreName))

{

log.error("Failed to get available core name:"+coreName);

throw new SolrServerException("No found out any solr server for a EMPTY core/collection name.");

}

SolrClient solrClient = null;

if(!SERVERS.containsKey(coreName))

{

solrClient = SolrClientSingleton.getSolrClientInstance(coreName);

SERVERS.put(coreName, solrClient);

}

else

{

solrClient = SERVERS.get(coreName);

}

if(solrClient == null)

{

log.error("No found any solr server for a specified core/collection name:"+coreName);

throw new SolrServerException("No found any solr server for a specified core/collection name:"+coreName);

}

return solrClient;

}

}

public class SolrClientSingleton

{

private static ISolrConfiguration config = new SolrConfiguration();

private SolrClientSingleton() {}

private static class SingletonHolder 

{  

private static final SolrClientSingleton INSTANCE = new SolrClientSingleton();  

}  

/**

* Get HttpSolrClient for a single node mode

* @returnSolrClient

*/

public static SolrClient getSolrClientInstance(String coreName)

{

return SingletonHolder.INSTANCE.createSolrClient(coreName); 

}

private SolrClient createSolrClient(String coreName) 

{

try

{

if(config.isCloudMode())

{

CloudSolrClient cloudSolrClient = new CloudSolrClient(config.getZkHosts());

cloudSolrClient.setDefaultCollection(coreName);

cloudSolrClient.connect();

cloudSolrClient.setZkConnectTimeout(config.getZkConnectionTimeout());

cloudSolrClient.setZkClientTimeout(config.getZkClientTimeout());

return cloudSolrClient;

}

else

{

HttpSolrClient httpSolrClient = new HttpSolrClient(getSolrURL(config.getUrl(),coreName));

httpSolrClient.setConnectionTimeout(config.getConnectionTimeout());

httpSolrClient.setDefaultMaxConnectionsPerHost(config.getMaxConnectionsPerHost());

httpSolrClient.setMaxTotalConnections(config.getMaxTotalConnections());

return httpSolrClient;

}

}

catch(Exception e)

{

log.error("Failed to connect to the solr server due to:"+e.toString());

throw new SolrServerException("Failed to connect to the solr server.");

}

}

/**

* Get a String of which is combined by Solr server url  and core name

* @param url

* @param coreName

* @return a url string

*/

private String getSolrURL(String url,String coreName)

{

if(StringUtils.isBlank(url) )

{

log.error("Solr url cannot be EMPTY.");

return null;

}

StringBuilder sb = new StringBuilder(url);

if(!url.endsWith("/"))

{

sb.append("/");

}

if(!StringUtils.isBlank(coreName))

{

sb.append(coreName);

}

return sb.toString();

}

}

猜你喜欢

转载自wingoal.iteye.com/blog/2289293