solr spring 简单封装
@PostConstructpublic void init() {
collectionName
= appEnv + "_" + searchCore;
// 查看collection是否存在,如果不存在需要构建collection
createCollectionWhenNotExist();
cloudSolrClient = new CloudSolrClient(zkHost);
cloudSolrClient.setDefaultCollection(collectionName);
cloudSolrClient.setZkClientTimeout(timeOut);
cloudSolrClient.setZkConnectTimeout(3000);
try {
cloudSolrClient.connect();
} catch (Exception e) {
LOGGER.error("solr connect error:{}", e.getMessage(), e);
}
}
private void createCollectionWhenNotExist() {
/**
* 查看配置的collection是否存在,如果不存在,1.上传solr配置.2.创建collection
*/
CloudSolrClient solrClient = new CloudSolrClient(zkHost);
solrClient.connect();
// 通过查询Collection的分布式情况,判断是否存在collection
CollectionAdminRequest.List collectionList = new CollectionAdminRequest.List();
ArrayList<String> collectionNames = new ArrayList<String>();
try {
CollectionAdminResponse response = collectionList.process(solrClient);
LinkedTreeMap<String, Object> responseMap = (LinkedTreeMap<String, Object>) gson.fromJson(response.toString(), Object.class);
collectionNames = (ArrayList<String>) responseMap.get("collections");
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (collectionNames.contains(collectionName)) {
return;
}
String configName = "solr_" + collectionName + "_config";
try {
PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = patternResolver.getResources(cfgPath);
File rourceFile = resources.getFile();
// 上传配置
String[] args = { "-cmd", "upconfig", "-zkhost", zkHost, "-confdir", rourceFile.getAbsolutePath(), "-confname", configName };
ZkCLI.main(args);
// 创建collection
CollectionAdminRequest.Create collectionCreate = new CollectionAdminRequest.Create();
collectionCreate.setCollectionName(collectionName);
collectionCreate.setConfigName(configName);
collectionCreate.setNumShards(numShards);
collectionCreate.process(solrClient);
} catch (Exception e) {
LOGGER.error("init solr collection error,collectionName:{} , errmsg:{}", collectionName, e.getMessage(), e);
}
}
@Override
public <T> void addDoc(String>
SolrInputDocument document = new SolrInputDocument();
document.addField("id",>
try {
Field field = doc.getClass().getDeclaredField("id");
field.setAccessible(true);
field.set(doc, "");
} catch (Exception e) {
// ignore
}
document.addField("content_sa", gson.toJson(doc));
try {
UpdateResponse res = cloudSolrClient.add(document);
LOGGER.info("solr add object success:{}", res);
cloudSolrClient.commit();
} catch (SolrServerException e) {
LOGGER.error("solr add object error,collection:{} doc:{} , errmsg:{}", collectionName, doc, e.getMessage(), e);
} catch (Exception e) {
LOGGER.error("solr add object error,collection:{} doc:{} , errmsg:{}", collectionName, doc, e.getMessage(), e);
}
}
页:
[1]