springboot和solr结合测试使用
首先新建springboot项目
新建webapp目录
springboot没有webapp目录——手动添加
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 5 version="4.0"> 6 <display-name>Archetype Created Web Application</display-name> 7 <filter> 8 <filter-name>encodingFilter</filter-name> 9 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 10 <init-param> 11 <param-name>encoding</param-name> 12 <param-value>UTF-8</param-value> 13 </init-param> 14 <init-param> 15 <param-name>forceEncoding</param-name> 16 <param-value>true</param-value> 17 </init-param> 18 </filter> 19 <filter-mapping> 20 <filter-name>encodingFilter</filter-name> 21 <url-pattern>/*</url-pattern> 22 </filter-mapping> 23 24 <listener> 25 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 26 </listener> 27 <listener> 28 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> 29 </listener> 30 <servlet> 31 <servlet-name>SpringMVC</servlet-name> 32 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 33 <init-param> 34 <param-name>contextConfigLocation</param-name> 35 <param-value>classpath:spring-mvc.xml</param-value> 36 </init-param> 37 <load-on-startup>1</load-on-startup> 38 <async-supported>true</async-supported> 39 </servlet> 40 <servlet-mapping> 41 <servlet-name>SpringMVC</servlet-name> 42 <url-pattern>/</url-pattern> 43 </servlet-mapping> 44 <welcome-file-list> 45 <welcome-file>/index</welcome-file> 46 </welcome-file-list> 47 </web-app>
spring-mvc.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:mvc="http://www.springframework.org/schema/mvc" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 8 xsi:schemaLocation="http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 12 http://www.springframework.org/schema/context 13 http://www.springframework.org/schema/context/spring-context-3.2.xsd 14 http://www.springframework.org/schema/aop 15 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 16 http://www.springframework.org/schema/tx 17 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> 18 19 <!-- 把Controller交给spring管理 --> 20 <context:component-scan base-package="com.xiaostudy"/> 21 22 <!-- 配置注解处理器映射器 功能:寻找执行类Controller --> 23 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> 24 25 <!-- 配置注解处理器适配器 功能:调用controller方法,执行controller --> 26 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> 27 28 <!-- 不用了 --> 29 <!-- 配置sprigmvc视图解析器:解析逻辑试图 30 后台返回逻辑试图:index 31 视图解析器解析出真正物理视图:前缀+逻辑试图+后缀====/WEB-INF/index.jsp --> 32 <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 33 <property name="prefix" value="/WEB-INF/"/> 34 <property name="suffix" value=".jsp"/> 35 </bean>--> 36 </beans>
application.yml
1 spring: 2 application: 3 name: solr 4 data: 5 solr: 6 host: http://127.0.0.1:8983/solr/test # test是core的名字,一定需要 7 server: 8 port: 8081 # springboot项目启动的端口号
base:User.java
1 package com.xiaostudy.solr_test1.base; 2 3 import org.apache.solr.client.solrj.beans.Field; 4 5 import java.io.Serializable; 6 7 /** 8 * Created with IntelliJ IDEA. 9 * User: Administrator 10 * Date: 2019/6/2 11 * Time: 11:10 12 * Description: No Description 13 */ 14 public class User implements Serializable { 15 //必须实现可序列化接口,要在网络上传输 16 @Field("user_id")//使用这个注释,里面的名字是根据你在solr数据库中配置的来决定 17 private String id; 18 @Field("user_name") 19 private String name; 20 @Field("user_sex") 21 private String sex; 22 @Field("user_address") 23 private String address; 24 25 public String getId() { 26 return id; 27 } 28 29 public void setId(String id) { 30 this.id = id; 31 } 32 33 public String getName() { 34 return name; 35 } 36 37 public void setName(String name) { 38 this.name = name; 39 } 40 41 public String getSex() { 42 return sex; 43 } 44 45 public void setSex(String sex) { 46 this.sex = sex; 47 } 48 49 public String getAddress() { 50 return address; 51 } 52 53 public void setAddress(String address) { 54 this.address = address; 55 } 56 }
controller:SolrController.java
package com.xiaostudy.solr_test1.web.controller; import com.xiaostudy.solr_test1.base.User; 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.client.solrj.response.UpdateResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.util.NamedList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 2019/6/2 * Time: 11:14 * Description: No Description */ @RestController public class SolrController { @Autowired private SolrClient solrClient; //批量增加 @RequestMapping("/addUsers") public void addUsers() throws IOException, SolrServerException { List<User> users = new ArrayList<>(); for(int i = 0; i < 3; i++) { User user = new User(); user.setId("123456_" + i); user.setName("xiaostudy_" + i); user.setAddress("广州_" + i); user.setSex("男_" + i); users.add(user); } solrClient.addBeans(users); solrClient.commit(); } //单个增加 @RequestMapping("/addUser") public void addUser() throws IOException, SolrServerException { User user = new User(); user.setId("45678"); user.setName("张三"); user.setAddress("北京市"); user.setSex("女"); solrClient.addBean(user); solrClient.commit(); } //根据id查询 @RequestMapping("/getByIdFromSolr/{id}") public void getByIdFromSolr(@PathVariable("id") String id) throws IOException, SolrServerException { //根据id查询内容 SolrDocument solrDocument = solrClient.getById(id); //获取filedName Collection<String> fieldNames = solrDocument.getFieldNames(); //获取file名和内容 Map<String, Object> fieldValueMap = solrDocument.getFieldValueMap(); // int childDocumentCount = solrDocument.getChildDocumentCount(); List<SolrDocument> childDocuments = solrDocument.getChildDocuments(); System.out.println("byId=================="+solrDocument); System.out.println("fieldNames=================="+fieldNames); System.out.println("fieldValueMap=================="+fieldValueMap); // System.out.println("childDocumentCount=================="+childDocumentCount); System.out.println("childDocuments=================="+childDocuments); } //根据di删除 @RequestMapping("/delById/{id}") public void delById(@PathVariable("id") String id) throws IOException, SolrServerException { //根据id删除信息 UpdateResponse updateResponse = solrClient.deleteById(id); //执行的时间 long elapsedTime = updateResponse.getElapsedTime(); int qTime = updateResponse.getQTime(); //请求地址 String requestUrl = updateResponse.getRequestUrl(); //请求的结果{responseHeader={status=0,QTime=2}} NamedList<Object> response = updateResponse.getResponse(); //请求结果的头{status=0,QTime=2} NamedList responseHeader = updateResponse.getResponseHeader(); //请求的状态 0 int status = updateResponse.getStatus(); System.out.println("elapsedTime==========="+elapsedTime); System.out.println("qTime==========="+qTime); System.out.println("requestUrl==========="+requestUrl); System.out.println("response==========="+response); System.out.println("responseHeader==========="+responseHeader); System.out.println("status==========="+status); } @RequestMapping("/queryFromSolr") public Object queryFromSolr() throws IOException, SolrServerException { //第一种方式 // Map<String, String> queryParamMap = new HashMap<String, String>(); // queryParamMap.put("q", "*:*"); // queryParamMap.put("f1","id,name"); // queryParamMap.put("sort","id asc"); // MapSolrParams mapSolrParams = new MapSolrParams(queryParamMap); // solrClient.query(mapSolrParams); //第二种方式 SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("*:*"); // solrQuery.addField("*"); solrQuery.add("q","id:4567"); solrQuery.setSort("id", SolrQuery.ORDER.asc); //设置查询的条数 solrQuery.setRows(50); //设置查询的开始 solrQuery.setStart(0); //设置高亮 solrQuery.setHighlight(true); //设置高亮的字段 solrQuery.addHighlightField("item_name"); //设置高亮的样式 solrQuery.setHighlightSimplePre("<font color='red'>"); solrQuery.setHighlightSimplePost("</font>"); System.out.println(solrQuery); QueryResponse response = solrClient.query(solrQuery); //返回高亮显示结果 Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); //response.getResults();查询返回的结果 SolrDocumentList documentList = response.getResults(); for (SolrDocument solrDocument : documentList) { System.out.println("solrDocument==============" +solrDocument); } return documentList; } }
测试能不能访问springboot项目,这个可以不要
IndexController.java
package com.xiaostudy.solr_test1.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 2019/6/2 * Time: 11:15 * Description: No Description */ @Controller public class IndexController { @RequestMapping("/index") public String index() { return "index"; } }
测试
所以这里提示:除了查询,增删改都要提交事务
solrClient.commit();
solrClient.addBean(new User());// 添加一个对象 solrClient.addBeans(users);// 添加多个对象 solrClient.deleteByQuery("*:*");// 删除所有索引 solrClient.deleteById("1234");// 删除id为1234的索引 solrClient.getById("1234");// 查询id为1234的索引
参考文章:https://blog.csdn.net/weixin_42129558/article/details/82682265