Solr
Apache Solr是一個搜尋引擎。Spring Boot為Solr 5用戶端library提供基本的自動配置,Spring Data Solr提供了在它之上的抽象,還有用于收集依賴的spring-boot-starter-data-solr’Starter’。

連接配接Solr
你可以注入一個自動配置的SolrClient執行個體,就像其他Spring beans那樣,該執行個體預設使用localhost:8983/solr連接配接Solr伺服器:
1@Component
2public class MyBean {
3 private SolrClient solr;
4 @Autowired
5 public MyBean(SolrClient solr) {
6 this.solr = solr;
7 }
8 // ...
9}
如果你添加自己的SolrClient類型的@Bean,它将會替換預設執行個體。
Spring Data Solr倉庫
Spring Data包含的倉庫也支援Apache Solr,正如先前讨論的JPA倉庫,基于方法名自動建立查詢是基本的原則。
實際上,不管是Spring Data JPA還是Spring Data Solr都共享相同的基礎設施。是以你可以使用先前的JPA示例,并假設那個City現在是一個@SolrDocument類而不是JPA @Entity,它将以同樣的方式工作。
Spring Data Solr入門小Demo
搭建工程
建立maven工程,pom.xml中引入依賴
1<parent>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-parent</artifactId>
4 <version>1.5.2.RELEASE</version>
5 </parent>
6 <properties>
7 <spring.data.solr.version>2.1.1.RELEASE</spring.data.solr.version>
8 </properties>
9 <dependencyManagement>
10 <dependencies>
11 <dependency>
12 <groupId>org.springframework.data</groupId>
13 <artifactId>spring-data-solr</artifactId>
14 <version>${spring.data.solr.version}</version>
15 </dependency>
16 </dependencies>
17 </dependencyManagement>
18 <dependencies>
19 <!--添加Web依賴, 使項目變成web項目-->
20 <dependency>
21 <groupId>org.springframework.boot</groupId>
22 <artifactId>spring-boot-starter-web</artifactId>
23 </dependency>
24 <dependency>
25 <groupId>org.springframework.data</groupId>
26 <artifactId>spring-data-solr</artifactId>
27 </dependency>
28 <!--test-->
29 <dependency>
30 <groupId>org.springframework.boot</groupId>
31 <artifactId>spring-boot-starter-test</artifactId>
32 </dependency>
33 </dependencies>
SpringBoot 快速啟動
1@SpringBootApplication
2@EnableAutoConfiguration
3public class AppMain {
4 public static void main(String[] args) {
5 SpringApplication.run(AppMain.class, args);
6 }
7}
可能遇見的問題:
- 一般spring-boot項目的啟動類都放在項目的根路徑下, 這樣可以不用配置@ComponentScan注解來掃描相應的類, 如果遇到無法讀取配置類屬性的情況, 首先考慮這個因素
在resources下建立application.properties, 完成solr的基本配置
1spring.data.solr.host=http://127.0.0.1:8983/solr
這個屬性配置的是solr伺服器的通路位址, 因為本項目是作為用戶端來通路solr伺服器, 是以不用做更多的配置
這個屬性是是通過@ConfigurationProperties("spring.data.solr")讀取出來的, 預設被讀取到 SolrProperties.class 中 詳情請使用類查找器檢視該類
1@RestController
2public class SolrController {
3 @Autowired
4 private SolrClient client;
5 @RequestMapping("/")
6 public String testSolr() throws IOException, SolrServerException {
7 SolrDocument document = client.getById("test", "fe7a5124-d75b-40b2-93fe-5555512ea6d2");
8 System.out.println(document);
9 return document.toString();
10 }
11}
1SolrDocument{goodsId=[129831], id=fe7a5124-d75b-40b2-93fe-5555512ea6d2, _version_=1562570354094768128}