上篇文章介紹了centos7.5 安裝solr的配置。今天介紹通過springboot2.0+spring-data-solr 完成一個Product對象的新增。也記錄下這次過程。
1、進入阿里雲centos系統,進入solr的bin目錄,創建一個collection,命令行代碼如下:
./solr create -c Product -force
由於我直接用root操作,所以後面加了-force ,強制執行
2、配置spring boot2.0 工程,pom文件導入依賴,如下截圖:
solr服務器我用的是最新的7.7.0
3、配置文檔類
建立Productde 文檔類,代碼如下:
@SolrDocument(collection = "Product")
public class Product {
\t@Id
\t@Indexed(name = "id", type = "string")
\tprivate String id;
\t@Indexed(name = "name", type = "string")
\tprivate String name;
\tpublic String getId() {
\t\treturn id;
\t}
\tpublic void setId(String id) {
\t\tthis.id = id;
\t}
\tpublic String getName() {
\t\treturn name;
\t}
\tpublic void setName(String name) {
\t\tthis.name = name;
\t}
}
4、定義ProductRepository接口,此類我們暫時只繼承Spring-data-solr提供的SolrCrudRepository,完成我們的新增和查詢是沒有問題的,
代碼如下:
public interface ProductRepository extends SolrCrudRepository<product> {
public List<product> findByName(String name);
}
/<product>/<product>
5、進行solr 持久層的spring配置,代碼如下:
@Configuration
@EnableSolrRepositories(
basePackages = "xin.clips")
@ComponentScan
public class SolrConfig {
@Value("${solr.host}") String solrURL;
@Bean
public SolrClient solrClient() {
return new HttpSolrClient.Builder(solrURL).build();
}
@Bean
public SolrTemplate solrTemplate(SolrClient client) throws Exception {
return new SolrTemplate(client);
}
}
備註:Value solr.host 配置在application.properties中,配置格式如:solr.host=http://xxx.xx.x.x:8983/solr/
6、寫我們的controller類,模擬新增和查詢,代碼如下:
/**
* @author www.clips.xin
* @description Product solr controller 示例
*/
@RestController
@RequestMapping("/api/product")
public class ProductController {
@Autowired
\tprivate ProductRepository productRepository;
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save() {
Product p = new Product();
p.setId("3");
p.setName("頭孢拉定膠囊");
productRepository.save(p);
System.out.println("插入成功!");
return null;
}
@RequestMapping(value = "/get", method = RequestMethod.POST)
public String get() {
List<product> list= productRepository.findByName("頭孢拉定膠囊");
Product p = list.get(0);
return "id"+p.getId()+",name:"+p.getName();
}
}
/<product>
7、啟動程序,postman進行測試,截圖如下:
瀏覽器打開:http://x.x.x.x:8983/solr/#/Product/core-overview 可以查看server端信息。
代碼地址:https://github.com/yuanzongyu/tutorials/tree/master/persistence-modules/spring-data-solr
閱讀更多 全棧獨立開發者 的文章