第一步添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
第二步修改yml文件
spring:
data:
solr: #注意修改ip地址
host: http://192.168.64.170:8983/solr/pd
第三步创建实体类pojo
@Field 是solr自定义的注解,用于与查询出来的json格式上属性名相同的元素进行匹配
package com.pd.pojo;
import java.io.Serializable;
import org.apache.solr.client.solrj.beans.Field;
import lombok.Data;
@Data
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
//@Field 是solr自定义的注解,用于与查询出来的json格式上属性名相同的元素进行匹配
@Field("id")
private String id;
@Field("title")
private String title;
@Field("sellPoint")
private String sellPoint;
@Field("price")
private Long price;
@Field("image")
private String image;
}
第四步创建对应的service接口,实现业务,构建实现类完成业务
package com.pd.service.impl;
import java.util.List;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import com.pd.pojo.Item;
import com.pd.service.SearchService;
@Service
public class SearchServiceImpl implements SearchService {
/*
* SolrClient实例是在 SolrAutoConfiguration 类中创建
* SolrAutoConfiguration添加了@Configuration注解,
* 是spring boot自动配置类,其中的solrClient()方法中创建了SolrClient实例
*/
@Autowired
private SolrClient solrClient;
@Override
public List<Item> findItemByKey(String key) throws Exception {
//构建solr的查询器更具用户传值进行查询
SolrQuery query = new SolrQuery(key);
//查询多少条数据,并进行分页
query.setStart(0);
query.setRows(20);
//执行查询并得到查询结果,封装的是一个json数据
QueryResponse qr = solrClient.query(query);
//其提供了转化给对象的方法,使用该方法获得对象
List<Item> beans = qr.getBeans(Item.class);
return beans;
}
}
第五步,实现控制层代码
package com.pd.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.pd.pojo.Item;
import com.pd.service.SearchService;
@Controller
public class SearchController {
@Autowired
private SearchService searchService;
@GetMapping("/search/toSearch.html")
public String search(String key, Model model) throws Exception {
List<Item> itemList = searchService.findItemByKey(key);
//model的name参数需要和jsp文件中设置的一样
model.addAttribute("list", itemList);
//yml文件没有加尾缀,需要全称
return "/search.jsp";
}
}