緊接上篇Solr搜索服務入門,這章主要是介紹solr集成spring實現搜索查詢服務....
直接擼代碼吧。。。。。。
主要步驟:
1、添加solr客戶端maven依賴
注意:選擇適合的版本,否則可能會與自身項目的一些jar依賴衝突,
<!-- solrJ客戶端 -->
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>5.3.1</version>
</dependency>
2、添加solr服務器信息
application.properties
#Solr
solrServer.url=http://localhost:8983/solr/test_core
solrServer.maxRetries=3
solrServer.connectionTimeout=500
3、新增spring-solr.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!--定義solr的server-->
<bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
<constructor-arg index="0" value="${solrServer.url}"/>
<!-- 設置響應解析器 -->
<property name="parser">
<bean class="org.apache.solr.client.solrj.impl.XMLResponseParser"/>
</property>
<!-- 設置重試次數-->
<property name="maxRetries" value="${solrServer.maxRetries}"/>
<!-- 建立連接的最長時間 -->
<property name="connectionTimeout" value="${solrServer.connectionTimeout}"/>
</bean>
</beans>
4、在主配置中引入spring-solr.xml
<!--集成Solr搜索 -->
<import resource="classpath:spring/spring-solr.xml"></import>
5、運行服務,測試
https://blog.csdn.net/xiaokang123456kao/article/details/72846591
https://www.cnblogs.com/anny0404/p/5235007.html
https://www.cnblogs.com/fengli9998/p/6475970.html
https://www.cnblogs.com/lizhangyong/p/8677921.html
@RequestMapping(value = "testSolrSelect", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> getTestSolr() throws Exception {
SolrQuery query = new SolrQuery();
query.set("q", "*:*");
query.set("fq", "");
query.set("fl", "**");
query.set("start", "0");
query.set("wt", "json");
QueryResponse queryResponse = httpSolrServer.query(query);
SolrDocumentList results = queryResponse.getResults();
for (SolrDocument result : results) {
Collection<String> fieldNames = result.getFieldNames();
for (String fieldName : fieldNames) {
System.out.println(fieldName + " ----> " + result.get(fieldName));
}
}
return null;
}