搭建solrcloud可以看之前的文章,这里主要记录一下springboot中使用solrCloud
博主的应用场景:三台solr,多个collection的情况
首先我们要明白,我们用zookeeper来管理solr ,这样我们在连接solr做增删改的时候就不需要再连solr了,这里直接连三个zk的集群
配置文件:
spring:
data:
solr:
repositories:
enabled: true
zk-host: 这里写你自己的zk地址
代码
这里可以直接在方法内build,也可以通过bean注入的方式
第一种
CloudSolrClient solrClient = new CloudSolrClient.Builder(Arrays.asList(ZK_HOST.split(",")), Optional.empty()).build();
client.setDefaultCollection(“这里写自己的collection”);
第二种
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
@Configuration
public class SearchConfig {
@Value("${spring.data.solr.zk-host}")
public String ZK_HOST;
/**
* 注入cloudSolrClient
*
* @return
*/
@Bean
public CloudSolrClient solrClient() {
CloudSolrClient solrClient = new CloudSolrClient.Builder(Arrays.asList(ZK_HOST.split(",")), Optional.empty()).build();
return solrClient;
}
}
service层:
@Autowired
private CloudSolrClient client;
public void test(){
client.setDefaultCollection(“这里写自己的collection”);
}
遇到的问题:
Exception in thread “main” java.lang.RuntimeException: Couldn’t initialize a HttpClusterStateProvider (is/are the Solr server(s), [localhost:8983], down?)
解决:
https://cloud.tencent.com/developer/ask/sof/105701440
主要是加上Optional.empty()