任何后端数据库,如 MySQL、Oracle、Redis、Solr、Elasticsearch、MongoDB
,在 SpringBoot 中,先经过 SpringData 的封装,都是无比优雅简洁的
附上使用 solr 模拟百度一下的搜索引擎实战案例:
使用 LayUI+SpringBoot+Solr 模仿百度一下搜索引擎
二、代码
2018.7.14更新:代码已经放在 github 上了:https://github.com/larger5/SpringBoot_solr_base.git
1、代码目录
2、Controller
package com.cun.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 优化:抽取 Id、text 为一个 JavaBean
* @author linhongcun
*
*/
@RestController
@RequestMapping("/test")
@EnableSwagger2
public class SolrController {
@Autowired
private SolrClient client;
/**
* 1、增
* @param message
* @return
* @throws IOException
* @throws SolrServerException
*/
@PostMapping("/insert")
public String insert(String message) throws IOException, SolrServerException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
String dateString = sdf.format(new Date());
try {
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id", dateString);
doc.setField("text", message);
/*
* 如果 spring.data.solr.host 里面配置到 core了, 那么这里就不需要传 collection1 这个参数 下面都是一样的 即
* client.commit();
*/
client.add("itaem", doc);
client.commit("itaem");
return dateString;
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
/**
* 2、查 id
* @param id
* @return
* @throws SolrServerException
* @throws IOException
*/
@GetMapping("/get/{id}")
public String getDocumentById(@PathVariable String id) throws SolrServerException, IOException {
SolrDocument document = client.getById("itaem", id);
System.out.println(document);
return document.toString();
}
/**
* 3、删 id
* @return
*/
@DeleteMapping("/delete/{id}")
public String getAllDocuments(@PathVariable String id) {
try {
client.deleteById("itaem", id);
client.commit("itaem");
return id;
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
/**
* 4、删 all
* @return
*/
@DeleteMapping("deleteAll")
public String deleteAll() {
try {
client.deleteByQuery("itaem", "*:*");
client.commit("itaem");
return "success";
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
/**
* 5、改
* @param message
* @return
* @throws IOException
* @throws SolrServerException
*/
@PutMapping("/update")
public String update(String id, String message) throws IOException, SolrServerException {
try {
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id", id);
doc.setField("text", message);
/*
* 如果 spring.data.solr.host 里面配置到 core了, 那么这里就不需要传 itaem 这个参数 下面都是一样的 即
* client.commit();
*/
client.add("itaem", doc);
client.commit("itaem");
return doc.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
/**
* 6、全:还没实现,也感觉没有必要实现
* @return
* @throws SolrServerException
* @throws IOException
*/
@GetMapping("/get/all")
public Map<String, Object> getAll()
throws SolrServerException, IOException {
Map<String, Object> map = new HashMap<String, Object>();
return map;
}
/**
* 7、查 ++:关键字、高亮、分页 ✔
* @return
* @return
* @throws SolrServerException
* @throws IOException
*/
@GetMapping("/select/{q}/{page}/{size}")
public Map<String, Object> select(@PathVariable String q, @PathVariable Integer page, @PathVariable Integer size)
throws SolrServerException, IOException {
SolrQuery params = new SolrQuery();
// 查询条件
params.set("q", q);
// 排序
params.addSort("id", SolrQuery.ORDER.desc);
// 分页
params.setStart(page);
params.setRows(size);
// 默认域
params.set("df", "text");
// 只查询指定域
params.set("fl", "id,text");
// 开启高亮
params.setHighlight(true);
// 设置前缀
params.setHighlightSimplePre("<span style='color:red'>");
// 设置后缀
params.setHighlightSimplePost("</span>");
// solr数据库是 itaem
QueryResponse queryResponse = client.query("itaem", params);
SolrDocumentList results = queryResponse.getResults();
// 数量,分页用
long total = results.getNumFound();// JS 使用 size=MXA 和 data.length 即可知道长度了(但不合理)
// 获取高亮显示的结果, 高亮显示的结果和查询结果是分开放的
Map<String, Map<String, List<String>>> highlight = queryResponse.getHighlighting();
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", total);
map.put("data", highlight);
return map;
}
}
3、yml
server:
context-path: /
port: 80
spring:
data:
solr:
host: http://120.79.197.131:8983/solr
三、效果
接口均经过 Swagger 测试,完全没有问题
1、可以打开 Solr 界面
http://120.79.197.131:8983/solr ,由于 这个 Solr 是在阿里云服务器
上,切使用 Docker
镜像搭建的,上面的报错瑕疵不必理会
2、接口测试
3、高亮效果
①先插入如下信息进入,以备查询
近期美国以中美贸易不平衡为由,对中国先采取滥用贸易救济措施的做法,接着挥舞美国国内生锈的301调查大棒,威胁要对中国600亿美元的商品征收高额关税,引起了全球资本市场的剧烈波动,也引发了中国和其他世
- 1
②查询
输入:美利坚合众国
- 1
③JSON显示
④页面显示
四、小结
参考文献
1、《SpringBoot 2 精髓》
李家智 著
2、Solr6 快速入门教程
3、Docker+Solr+IK
4、solr(四) : springboot 整合 solr
<li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
<use xlink:href="#csdnc-thumbsup"></use>
</svg><span class="name">点赞</span>
<span class="count">3</span>
</a></li>
<li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{"mod":"popu_824"}"><svg class="icon" aria-hidden="true">
<use xlink:href="#icon-csdnc-Collection-G"></use>
</svg><span class="name">收藏</span></a></li>
<li class="tool-item tool-active is-share"><a href="javascript:;" data-report-click="{"mod":"1582594662_002"}"><svg class="icon" aria-hidden="true">
<use xlink:href="#icon-csdnc-fenxiang"></use>
</svg>分享</a></li>
<!--打赏开始-->
<!--打赏结束-->
<li class="tool-item tool-more">
<a>
<svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
</a>
<ul class="more-box">
<li class="item"><a class="article-report">文章举报</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="person-messagebox">
<div class="left-message"><a href="https://blog.csdn.net/larger5">
<img src="https://profile.csdnimg.cn/3/D/3/3_larger5" class="avatar_pic" username="larger5">
<img src="https://g.csdnimg.cn/static/user-reg-year/2x/3.png" class="user-years">
</a></div>
<div class="middle-message">
<div class="title"><span class="tit"><a href="https://blog.csdn.net/larger5" data-report-click="{"mod":"popu_379"}" target="_blank">larger5</a></span>
</div>
<div class="text"><span>发布了104 篇原创文章</span> · <span>获赞 459</span> · <span>访问量 87万+</span></div>
</div>
<div class="right-message">
<a href="https://bbs.csdn.net/topics/395525761" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-messageboard">他的留言板
</a>
<a class="btn btn-sm attented bt-button personal-watch" data-report-click="{"mod":"popu_379"}">已关注</a>
</div>
</div>
</div>