Spring Boot集成Sorl搜索客户端的实现代码
ApacheSolr是一个搜索引擎。SpringBoot为solr客户端库及SpringDataSolr提供的基于solr客户端库的抽象提供了基本的配置。SpringBoot提供了一个用于聚集依赖的spring-boot-starter-data-solr'StarterPOM'。
引入spring-boot-starter-data-solr依赖,在pom.xml配置文件中增加如下内容(基于之前章节“SpringBoot构建框架”中的pom.xml文件):
org.springframework.boot spring-boot-starter-data-solr
可以像其他Springbeans一样注入一个自动配置的SolrServer实例。默认情况下,该实例将尝试使用localhost:8983/solr连接一个服务器。
@Component
publicclassMyBean{
privateSolrServersolr;
@Autowired
publicMyBean(SolrServersolr){
this.solr=solr;
}
//...
}
如果添加一个自己的SolrServer类型的@Bean,它将会替换默认的。
应用集成Solr搜索客户端案例
SpringBoot的配置是集中性的(可以拆分成不同的配置文件),因此在application.properties文件中添加以下配置:
#SOLR(SolrProperties) spring.data.solr.host=http://localhost:8983/solr #spring.data.solr.zkHost= spring.data.solr.repositories.enabled=true
使用Spring-data-solr类似spring-data-jpa,配置@bean接受zk服务器相关属性(自定义的配置方式,可以直接使用默认方式)
importorg.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix="spring.solr")
publicclassSolrConfig{
privateStringhost;
privateStringzkHost;
privateStringdefaultCollection;
publicStringgetDefaultCollection(){
returndefaultCollection;
}
publicvoidsetDefaultCollection(StringdefaultCollection){
this.defaultCollection=defaultCollection;
}
publicStringgetHost(){
returnhost;
}
publicvoidsetHost(Stringhost){
this.host=host;
}
publicStringgetZkHost(){
returnzkHost;
}
publicvoidsetZkHost(StringzkHost){
this.zkHost=zkHost;
}
配置SolrServer服务,具体代码如下:
@Configuration
@EnableConfigurationProperties(SolrConfig.class)
publicclassSolrClientConfig{
@Autowired
privateSolrConfigsolrConfig;
privateCloudSolrServersolrServer;
@PreDestroy
publicvoidclose(){
if(this.solrServer!=null){
try{
this.solrServer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
@Bean
publicCloudSolrServerSolrServer(){
if(StringUtils.hasText(this.solrConfig.getZkHost())){
solrServer=newCloudSolrServer(this.solrConfig.getZkHost());
solrServer.setDefaultCollection(this.solrConfig.getDefaultCollection());
}
returnthis.solrServer;
}
}
测试solr查询,具体代码如下:
@RestController
publicclassHelloController{
@Autowired
privateCloudSolrServersolrserver;
publicStringhello(){
return"sayhello";
}
@RequestMapping("test")
publicvoidtest(){
ModifiableSolrParamsparams=newModifiableSolrParams();
params.add("q","demo:素文宅博客");
params.add("ws","json");
params.add("start","0");
params.add("rows","10");
QueryResponseresponse=null;
try{
response=solrserver.query(params);
SolrDocumentListresults=response.getResults();
for(SolrDocumentdocument:results){
System.out.println(document.getFieldValue("demo"));
System.out.println(document.getFieldValue("id"));
}
}catch(Exceptione){
e.getStackTrace();
}
System.out.println(response.toString());
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。