springboothe整合solr

第一步添加依赖

<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";
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值