赞
踩
一:案列需求:
1)使用技术 springMVC+Spring+Mybatis+solrJ
2) 将 mysql 中的 tb_item 表中的部分业务数据导入到 solr 的索引库中
3) 提供一个搜索页面,在搜索页面中完成数据搜索
二:使用软件:IDEA。使用MAVEN管理项目。
先搭建环境
1.SolrParent:pom.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <packaging>pom</packaging>
- <groupId>com.bjsxt</groupId>
- <artifactId>SolrParent</artifactId>
- <version>1.0-SNAPSHOT</version>
-
- <!-- 对依赖的jar包的版本统一进行定义 -->
- <properties>
- <solrj.version>4.10.3</solrj.version>
- <jedis.version>2.9.0</jedis.version>
- <junit.version>4.12</junit.version>
- <spring.version>4.1.3.RELEASE</spring.version>
- <mybatis.version>3.2.8</mybatis.version>
- <mybatis.spring.version>1.2.2</mybatis.spring.version>
- <mysql.version>5.1.32</mysql.version>
- <slf4j.version>1.6.4</slf4j.version>
- <druid.version>1.0.9</druid.version>
- <jstl.version>1.2</jstl.version>
- <servlet-api.version>2.5</servlet-api.version>
- <tomcat.version>2.2</tomcat.version>
- <jsp-api.version>2.0</jsp-api.version>
- <zkClient-version>0.10</zkClient-version>
- <dubbo-version>2.5.4</dubbo-version>
- <jackson.version>2.4.2</jackson.version>
- <commons-net.version>3.3</commons-net.version>
- <commons-fileupload.version>1.3.1</commons-fileupload.version>
- </properties>
-
-
- <!-- jar包的依赖注入 ,由于该工程是一个父工程,所以jar包在该pom文件中只是声明 -->
- <dependencyManagement>
- <dependencies>
-
- <dependency>
- <groupId>org.apache.solr</groupId>
- <artifactId>solr-solrj</artifactId>
- <version>${solrj.version}</version>
- </dependency>
- <dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- <version>${jedis.version}</version>
- </dependency>
- <!-- 单元测试 -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>${junit.version}</version>
- </dependency>
- <!-- 日志处理 -->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>${slf4j.version}</version>
- </dependency>
- <!-- Mybatis -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>${mybatis.version}</version>
- </dependency>
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis-spring</artifactId>
- <version>${mybatis.spring.version}</version>
- </dependency>
- <!-- MySql -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>${mysql.version}</version>
- </dependency>
- <!-- 连接池 -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>${druid.version}</version>
- </dependency>
- <!-- Spring -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <!-- JSP相关 -->
- <dependency>
- <groupId>jstl</groupId>
- <artifactId>jstl</artifactId>
- <version>${jstl.version}</version>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>${servlet-api.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jsp-api</artifactId>
- <version>${jsp-api.version}</version>
- <scope>provided</scope>
- </dependency>
- <!-- 文件上传组件 -->
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>${commons-fileupload.version}</version>
- </dependency>
-
- <dependency>
- <groupId>commons-net</groupId>
- <artifactId>commons-net</artifactId>
- <version>${commons-net.version}</version>
- </dependency>
-
- <!-- Jackson Json处理工具包 -->
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <build>
- <resources>
- <resource>
- <directory>src/main/java</directory>
- <includes>
- <include>**/*.xml</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- </resources>
- <!-- tomcat插件,由于子项目不一定每个都是web项目,所以该插件只是声明,并未开启 -->
- <pluginManagement>
- <plugins>
- <!-- 配置Tomcat插件 -->
- <plugin>
- <groupId>org.apache.tomcat.maven</groupId>
- <artifactId>tomcat7-maven-plugin</artifactId>
- <version>${tomcat.version}</version>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
- </project>
2.SolrZH:pom.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <artifactId>SolrParent</artifactId>
- <groupId>com.bjsxt</groupId>
- <version>1.0-SNAPSHOT</version>
- <relativePath>../SolrParent/pom.xml</relativePath>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.bjsxt</groupId>
- <version>1.0-SNAPSHOT</version>
- <artifactId>SolrZH</artifactId>
- <packaging>war</packaging>
-
-
- <dependencies>
- <dependency>
- <groupId>org.apache.solr</groupId>
- <artifactId>solr-solrj</artifactId>
- </dependency>
- <!-- 单元测试 -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- </dependency>
- <!-- 日志处理 -->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </dependency>
- <!-- Mybatis -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- </dependency>
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis-spring</artifactId>
- </dependency>
- <!-- MySql -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
- <!-- 连接池 -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- </dependency>
- <!-- Spring -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
- </dependency>
- <!-- JSP相关 -->
- <dependency>
- <groupId>jstl</groupId>
- <artifactId>jstl</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jsp-api</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-
- <build>
- <resources>
- <resource>
- <directory>src/main/java</directory>
- <includes>
- <include>**/*.xml</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- </resources>
- <!-- tomcat插件,由于子项目不一定每个都是web项目,所以该插件只是声明,并未开启 -->
- <plugins>
- <!-- 配置Tomcat插件 -->
- <plugin>
- <groupId>org.apache.tomcat.maven</groupId>
- <artifactId>tomcat7-maven-plugin</artifactId>
- <configuration>
- <path>/</path>
- <port>8080</port>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-
- </project>
3.resources:mybatis-->SqlMapperClient.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <!-- 配置分页插件 -->
- </configuration>
resources:resource-->db.properties
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
- jdbc.username=root
- jdbc.password=root
resources:resource-->resource.properties
- SOLR_SERVICE_URL=http://192.168.92.135:8080/solr
- SOLR_CLOUD_SERVICE_URL=192.168.92.135:2181,192.168.92.135:2182,192.168.92.135:2183
- DEFAULT_COLLECTION=collection2
4.resources:spring:以下代码为图片中顺序
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <!-- 配置解析properties文件的工具类 -->
- <context:property-placeholder location="classpath:resource/*.properties"/>
-
- <!-- 配置数据源 dataSource -->
- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- <property name="driverClassName" value="${jdbc.driver}" />
- <property name="maxActive" value="10" />
- <property name="minIdle" value="5" />
- </bean>
-
- <!-- 创建mybatis的上下文对象 -->
- <bean class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource">
- <ref bean="dataSource"/>
- </property>
- <property name="configLocation">
- <value>classpath:mybatis/SqlMapperClient.xml</value>
- </property>
- </bean>
-
- <!-- 扫描mybatis的接口与映射配置文件 -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="com.bjsxt.mapper"/>
- </bean>
- </beans>
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <!-- 扫描bean对象 -->
- <context:component-scan base-package="com.bjsxt.service,com.bjsxt.dao"/>
- </beans>
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <!-- 整个单机版solr-->
- <!--<bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
- <constructor-arg name="baseURL">
- <value>${SOLR_SERVICE_URL}</value>
- </constructor-arg>
- </bean>-->
-
- <!--整合集群版solr-->
- <bean id="cloudSolrServer" class="org.apache.solr.client.solrj.impl.CloudSolrServer">
- <constructor-arg name="zkHost">
- <value>${SOLR_CLOUD_SERVICE_URL}</value>
- </constructor-arg>
- <property name="defaultCollection">
- <value>${DEFAULT_COLLECTION}</value>
- </property>
- </bean>
- </beans>
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
- <!-- 配置事物管理器的切面 -->
- <bean id="transactionMananger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"/>
- </bean>
-
- <!-- 配置事物传播行为 :其实就是那些方法应该受什么样的事物控制-->
- <tx:advice id="advice" transaction-manager="transactionMananger">
- <tx:attributes>
- <tx:method name="add*" propagation="REQUIRED"/>
- <tx:method name="modify*" propagation="REQUIRED"/>
- <tx:method name="update*" propagation="REQUIRED"/>
- <tx:method name="dorp*" propagation="REQUIRED"/>
- <tx:method name="del*" propagation="REQUIRED"/>
- <tx:method name="find*" read-only="true"/>
- </tx:attributes>
- </tx:advice>
-
- <!-- 那些类下的方法需要参与到当前的事物管理中 。配置切点 -->
- <aop:config>
- <aop:advisor advice-ref="advice" pointcut="execution(* com.bjsxt.service.*.*(..))"/>
- </aop:config>
- </beans>
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <!-- 包的扫描器主要是扫描@controller -->
- <context:component-scan base-package="com.bjsxt.web.controller"/>
-
- <!-- 注册两个新对象 主要是为了来处理springmvc中的其他anntation 如:@requestmapping -->
- <mvc:annotation-driven/>
-
- <!-- 视图解析器 -->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/jsp/" /><!-- jsp所在的前缀 -->
- <property name="suffix" value=".jsp" />
- </bean>
- <!-- 配置静态资源映射 -->
- <!--<mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
- <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>-->
- </beans>
5.webapp:WEB-INF-->web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
- id="WebApp_ID" version="3.0">
- <!-- 上下文参数,告诉Spring配置文件路径 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring/applicationContext-*.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
-
- <!-- 配置springmvc -->
- <servlet>
- <servlet-name>springmvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring/springmvc.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>springmvc</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
-
- <filter>
- <filter-name>encoding</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>utf-8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encoding</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
-
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- <welcome-file>index.htm</welcome-file>
- <welcome-file>index.jsp</welcome-file>
- <welcome-file>default.html</welcome-file>
- <welcome-file>default.htm</welcome-file>
- <welcome-file>default.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
此图为整个案列的环境
三:实现功能1:从数据库中获取数据添加到Solr索引库中:数据为商品数据
1.pojo-->TbItem
- package com.bjsxt.pojo;
-
- import java.io.Serializable;
- import java.util.Date;
-
- public class TbItem implements Serializable {
- private Long id;
-
- private String title;
-
- private String sell_Point;
-
- private Long price;
-
- private Integer num;
-
- private String barcode;
-
- private String image;
-
- private Long cid;
-
- private Byte status;
-
- private Date created;
-
- private Date updated;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title == null ? null : title.trim();
- }
-
-
- public String getSell_Point() {
- return sell_Point;
- }
-
- public void setSell_Point(String sell_Point) {
- this.sell_Point = sell_Point;
- }
-
- public Long getPrice() {
- return price;
- }
-
- public void setPrice(Long price) {
- this.price = price;
- }
-
- public Integer getNum() {
- return num;
- }
-
- public void setNum(Integer num) {
- this.num = num;
- }
-
- public String getBarcode() {
- return barcode;
- }
-
- public void setBarcode(String barcode) {
- this.barcode = barcode == null ? null : barcode.trim();
- }
-
- public String getImage() {
- return image;
- }
-
- public void setImage(String image) {
- this.image = image == null ? null : image.trim();
- }
-
- public Long getCid() {
- return cid;
- }
-
- public void setCid(Long cid) {
- this.cid = cid;
- }
-
- public Byte getStatus() {
- return status;
- }
-
- public void setStatus(Byte status) {
- this.status = status;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- public Date getUpdated() {
- return updated;
- }
-
- public void setUpdated(Date updated) {
- this.updated = updated;
- }
- }
2.mapper-->ItemMapper
- package com.bjsxt.mapper;
-
- import com.bjsxt.pojo.TbItem;
-
- import java.util.List;
-
- public interface ItemMapper {
-
- List<TbItem> findAll();
- }
mapper-->ItemMapper.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
- <mapper namespace="com.bjsxt.mapper.ItemMapper">
- <select id="findAll" resultType="com.bjsxt.pojo.TbItem">
- select * from tb_item
- </select>
- </mapper>
3.service-->ImportItemService----ImportItemServiceImpl
- package com.bjsxt.service;
-
- import com.bjsxt.pojo.TbItem;
-
- import java.util.List;
-
- public interface ImportItemService {
-
- void importItem();
- }
- package com.bjsxt.service.impl;
-
- import com.bjsxt.mapper.ItemMapper;
- import com.bjsxt.pojo.TbItem;
- import com.bjsxt.service.ImportItemService;
- import org.apache.solr.client.solrj.impl.CloudSolrServer;
- import org.apache.solr.common.SolrInputDocument;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.ArrayList;
- import java.util.List;
-
- /**
- * 从数据库中获取数据导入索引库
- */
- @Service
- public class ImportItemServiceImpl implements ImportItemService {
- @Autowired
- private ItemMapper itemMapper;
- @Autowired
- private CloudSolrServer cloudSolrServer;
- @Override
- public void importItem() {
- try {
- //查询数据库所以数据
- List<TbItem> list = this.itemMapper.findAll();
- //创建文档集合模型
- List<SolrInputDocument> result=new ArrayList<>();
- //遍历数据并创建索引库文档导入文档中
- for(TbItem item:list){
- //创建文档
- SolrInputDocument document=new SolrInputDocument();
- //讲数据库中部分数据放入文档中
- document.addField("id",item.getId()+"");
- document.addField("item_title",item.getTitle());
- document.addField("item_sell_point",item.getSell_Point());
- document.addField("item_price",item.getPrice());
- document.addField("item_image",item.getImage());
- //添加文档数据到文档模型中
- result.add(document);
- }
- this.cloudSolrServer.add(result);
- this.cloudSolrServer.commit();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
3.Controller-->ImportDataController
- package com.bjsxt.web.controller;
-
- import com.bjsxt.service.ImportItemService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.stereotype.Service;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- /**
- * 导入商品数据Controller
- */
- @Controller
- @RequestMapping("/import")
- public class ImportDataController {
- @Autowired
- private ImportItemService importItemService;
- @RequestMapping("/importData")
- public String importData(){
- this.importItemService.importItem();
- return "ok";
- }
- }
4.结果如图:
四:实现功能2:在Solr索引库中搜索获取数据在页面展示
1.pojo-->PageResult
- package com.bjsxt.pojo;
-
- import java.io.Serializable;
- import java.util.List;
-
- public class PageResult implements Serializable {
-
- private List<TbItem> result;//结果集
-
- private Integer indexPage;//当前页
-
- private Long totalPage;//总页数
-
- private Long totalNum;//总条数
-
- public List<TbItem> getResult() {
- return result;
- }
-
- public void setResult(List<TbItem> result) {
- this.result = result;
- }
-
- public Integer getIndexPage() {
- return indexPage;
- }
-
- public void setIndexPage(Integer indexPage) {
- this.indexPage = indexPage;
- }
-
- public Long getTotalPage() {
- return totalPage;
- }
-
- public void setTotalPage(Long totalPage) {
- this.totalPage = totalPage;
- }
-
- public Long getTotalNum() {
- return totalNum;
- }
-
- public void setTotalNum(Long totalNum) {
- this.totalNum = totalNum;
- }
- }
2.dao-->SolrSearchItemDao----SolrSearchItemDaoImpl
- package com.bjsxt.dao;
-
- import com.bjsxt.pojo.PageResult;
- import org.apache.solr.client.solrj.SolrQuery;
-
- public interface SolrSearchItemDao {
-
- PageResult searchItem(SolrQuery solrQuery) throws Exception;
- }
- package com.bjsxt.dao.impl;
-
- import com.bjsxt.dao.SolrSearchItemDao;
- import com.bjsxt.pojo.PageResult;
- import com.bjsxt.pojo.TbItem;
- import org.apache.solr.client.solrj.SolrQuery;
- import org.apache.solr.client.solrj.impl.CloudSolrServer;
- import org.apache.solr.client.solrj.response.QueryResponse;
- import org.apache.solr.common.SolrDocument;
- import org.apache.solr.common.SolrDocumentList;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Repository;
-
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
-
- /**
- * 查询solr
- */
- @Repository
- public class SolrSearchItemDaoImpl implements SolrSearchItemDao {
- @Autowired
- private CloudSolrServer cloudSolrServer;
- @Override
- public PageResult searchItem(SolrQuery solrQuery) throws Exception {
- //1.执行查询
- QueryResponse res = this.cloudSolrServer.query(solrQuery);
- //2.得到查询结果集
- SolrDocumentList list = res.getResults();
- //3.处理结果集
- //创建接收页面对象
- PageResult page = new PageResult();
- //3.1.页面获得总条数
- page.setTotalNum(list.getNumFound());
- //3.2.获取数据结果集
- //创建集合模型
- List<TbItem> items=new ArrayList<>();
- //获取高亮信息
- Map<String ,Map<String,List<String>>> hl=res.getHighlighting();
- //模型转换————》把索引库数据(文档)转换成页面接收数据(结果数据)
- for(SolrDocument var :list){
- //创建商品对象
- TbItem item=new TbItem();
- //设置每个商品信息的属性
- item.setId(Long.parseLong((String)var.get("id")));
- //item.setTitle((String)var.get("item_title"));
- item.setSell_Point((String)var.get("item_sell_point"));
- item.setPrice((Long) var.get("item_price"));
- item.setImage((String)var.get("item_image"));
- //由于对搜索关键字item_title设为高亮:所以需要对item_title判断是否为关键字,
- List<String> h = hl.get(var.get("id")).get("item_title");
- String title="";//设置变量title用于代替item_title
- if(h!=null && h.size()>0){//是关键字
- title = h.get(0);
- }else {//不是关键字,无高亮标识
- title=(String)var.get("item_title");
- }
- item.setTitle(title);
- //将商品对象放在商品集合中
- items.add(item);
- }
- //将结果放在页面对象中
- page.setResult(items);
-
-
- return page;
- }
- }
3.service-->SearchItemService----SearchItemServiceImpl
- package com.bjsxt.service;
-
- import com.bjsxt.pojo.PageResult;
-
- public interface SearchItemService {
-
- PageResult searchItem(String query, Integer page, Integer rows) throws Exception;
- }
- package com.bjsxt.service.impl;
-
- import com.bjsxt.dao.SolrSearchItemDao;
- import com.bjsxt.pojo.PageResult;
- import com.bjsxt.service.SearchItemService;
- import org.apache.solr.client.solrj.SolrQuery;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- /**
- * 完成solr搜索业务
- *
- *
- */
- @Service
- public class SearchItemServiceImpl implements SearchItemService {
- @Autowired
- private SolrSearchItemDao solrSearchItemDao;
- @Override
- public PageResult searchItem(String query, Integer page, Integer rows) throws Exception {
- //1.创建查询条件
- SolrQuery solrQuery=new SolrQuery();
- //2.设置查询条件
- //查询关键字
- solrQuery.setQuery(query);
- //查询域
- solrQuery.set("df","item_keywords");
- //分页查询
- solrQuery.setStart((page-1)*rows);
- solrQuery.setRows(rows);
- //设置高亮
- solrQuery.setHighlight(true);//开启高亮
- solrQuery.addHighlightField("item_title");//设置高亮位置
- solrQuery.setHighlightSimplePre("<em style='color:red'>");//设置高亮样式
- solrQuery.setHighlightSimplePost("</em>");//设置高亮样式
- //3.调用solrSearchItemDao
- PageResult result = solrSearchItemDao.searchItem(solrQuery);
- //补齐dao层未获取数据
- //3.3获取当前页
- result.setIndexPage(page);
- //3.4获取总页数
- Long total=result.getTotalNum()/rows;
- if(result.getTotalNum()% rows>0){
- total++;//总条数除以行数 余数大于0 ,则新加一页
- }
- result.setTotalPage(total);
-
-
-
- return result;
- }
- }
4.Controller-->SearchItemController
- package com.bjsxt.web.controller;
-
- import com.bjsxt.pojo.PageResult;
- import com.bjsxt.service.SearchItemService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
-
- /**
- * 查询商品Controller
- */
- @Controller
- @RequestMapping("/search")
- public class SearchItemController {
- @Autowired
- private SearchItemService searchItemService;
- @RequestMapping("/searchItem")
- public String SearchItem(String query, @RequestParam(value = "page",defaultValue = "1") Integer page, @RequestParam(value = "rows",defaultValue = "2") Integer rows, Model model){
- try {
- PageResult result = this.searchItemService.searchItem(query, page, rows);
- model.addAttribute("result",result);
- }catch (Exception e){
- e.printStackTrace();
- }
- return "showItem";
- }
- }
5.jsp-->index.jsp-----showItem.jsp
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2019/10/9
- Time: 11:10
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <form action="search/searchItem" method="post">
- <input type="text" name="query">
- <input type="submit" value="搜索">
- </form>
- </body>
- </html>
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2019/10/9
- Time: 17:44
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <span>当前页:${result.indexPage}</span>
- <span>总页数:${result.totalPage}</span>
- <span>总条数:${result.totalNum}</span>
-
- <table align="center" border="1">
- <c:forEach items="${result.result}" var="item">
- <tr>
- <td>${item.id}</td>
- <td>${item.title }</td>
- <td>${item.sell_Point }</td>
- <td>${item.price }</td>
- <td>${item.image }</td>
- </tr>
- </c:forEach>
- </table>
- </body>
- </html>
结果如图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。