美文网首页
Java高级技术day82:solr集群

Java高级技术day82:solr集群

作者: 开源oo柒 | 来源:发表于2019-11-14 21:02 被阅读0次

    一、SolrCloud

    1.什么是SolrCloud?

    SolrCloud(solr 云)是 Solr 提供的分布式搜索方案,当你需要大规模,容错,分布 式索引和检索能力时使用 SolrCloud。当一个系统的索引数据量少的时候是不需要使用 SolrCloud 的,当索引量很大,搜索请求并发很高,这时需要使用 SolrCloud 来满足这些 需求。

    • SolrCloud的原理:

    SolrCloud 是基于 Solr 和 Zookeeper 的分布式搜索方案,它的主要思想是使用 Zookeeper 作为集群的配置信息中心。 它有几个特色功能:
    (1)集中式的配置信息;
    (2)自动容错;
    (3)近实时搜索 ;
    (4)查询时自动负载均衡;

    • Solr集群结构图:


      结构
    • Solr伪集群搭建设计:

    本次集群采用伪集群的方式进行安装,如果是真正的生产环境,建议搭建真实集群。SolrCloud 结构图如下:

    结构图

    2.搭建Solr集群环境:

    (1)在 192.168.226.130 环境中安装 zookeeper 集群(已安装);
    (2)创建 4 个 tomcat 实例,修改其端口为 8080-8083;
    (3)使用已安装好的单机版 solr 作为集群的节点使用。

    2.1 创建solrcloud目录:

    mkdir solrcloud;
    在该目录下拷贝4个Tomcat示例和4个solr索引库;

    创建目录 拷贝文件
    • 修改Tomcat的端口:


      修改文件目录
    [图片]
    [示例]
    示例
    • 修改solr服务中指向solr索引库的路径:


      修改文件的目录[图片上传中]
      修改内容
    • 启动zookeeper集群查看状态:


      zookeeper集群状态
    2.2创建集群:

    把 solrhome 中的配置文件上传到 zookeeper 集群。使用 zookeeper 的客户端上传;执行下面命令时,确保zookeeper集群启动正常;
    “./zkcli.sh -zkhost 192.168.70.147:2181, 192.168.70.147:2182, 192.168.70.147:2183 -cmd upconfig -confdir /usr/local/solrcloud/solrhome1/solr/collection1/conf -confname myconf ”;

    示例
    • 切换到zookeeper集群:

    进入任意一个zookeeper中查看连接客户端查看。

    示例! 示例
    • 修改solrhome下的solr.xml文件:

    指定当前示例运行的ip地址及端口号;

    修改的目录
    修改内容
    • 修改tomcat 的 bin 目录下 catalina.sh 文件:

    修改每一台 solr的 tomcat 的 bin 目录下 catalina.sh 文件中
    加入 DzkHost 指定 zookeeper 服务器地址。
    JAVA_OPTS="-DzkHost=192.168.70.147:2181,192.168.70.147:2182,192.168.70.14 7:2183" ;

    修改文件的目录
    示例

    3.启动Tomcat测试:

    启动Tomcat
    • 打开浏览器访问

    访问集群中的任意一个;

    成功界面

    4.操作逻辑索引库:

    • 创建新的逻辑索引库并分片 :

    创建一个新的 collection,并分两片,每片是一主一备。
    使用以下命令创建:

    http://192.168.70.147:8080/solr/admin/collections?action=CREATE&name=collec tion2&numShards=2&replicationFactor=2 
    
    • 删除原来的逻辑索引库:
    http://192.168.70.147:8080/solr/admin/collections?action=DELETE&name=collec tion1 
    

    二、使用SolrJ操作集群

    1.在集群中添加文档:

    • 修改POM文件:
            <!-- https://mvnrepository.com/artifact/org.apache.solr/solr-solrj -->
            <dependency>
                <groupId>org.apache.solr</groupId>
                <artifactId>solr-solrj</artifactId>
                <version>4.10.3</version>
            </dependency>
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.2</version>
            </dependency>
    
    • 在集群中添加文档:
    /**
         * 向集群的索引中添加文档
         * @throws IOException 
         * @throws SolrServerException 
         */
        private static void solrCloudInsert() throws Exception {
            // zookeeper地址
            String zlhost = "192.168.226.130:2181,192.168.226.130:2182,192.168.226.130:2183";
            // 创建solrCloud对象
            CloudSolrServer cloud = new CloudSolrServer(zlhost);
    
            // 设置索引库
            cloud.setDefaultCollection("collection2");
            SolrInputDocument document= null;
            for (int i = 1; i < 10; i++) {
                // 创建solr文档对象
                document = new SolrInputDocument();
                document.addField("id", "test"+i);
                document.addField("item_title", "hello"+i);
                document.addField("item_price", 100+i);
                cloud.add(document);
            }
            cloud.commit();
            cloud.shutdown();
        }
    

    2.删除集群中的文档 :

        /**
         * 删除集群中的文档
         * @throws Exception
         */
        private static void solrCloudDel() throws Exception {
            //zookeeper地址
            String zlhost = "192.168.226.130:2181,192.168.226.130:2182,192.168.226.130:2183";
            //创建solrCloud对象
            CloudSolrServer server = new CloudSolrServer(zlhost);
            
            server.setDefaultCollection("collection2");
            server.deleteByQuery("*:*");
            server.commit();
            server.shutdown();
        }
    

    3. 查询集群中的文档 :

        /**
         * 查询集群中的文档
         * @throws SolrServerException 
         * @throws Exception
         */
        private static void solrCloudSearch() throws SolrServerException {
            //zookeeper地址
            String zkhost = "192.168.226.130:2181,192.168.226.130:2182,192.168.226.130:2183";
            //创建solrCloud对象
            CloudSolrServer server = new CloudSolrServer(zkhost);
            server.setDefaultCollection("collection2");
            //常见查询对象
            SolrQuery query = new SolrQuery();
            query.setQuery("hello");
            query.set("df","item_keywords");
            query.setStart(0);
            query.setRows(10);
            //开始查询
            QueryResponse re = server.query(query);
            SolrDocumentList list = re.getResults();
            System.out.println("总条数:"+list.getNumFound());
            for (SolrDocument document : list) {
                System.out.println(document.get("item_title"));
                System.out.println(document.get("item_price"));
            }
        }
    

    三、Solr实例:

    (1)使用技术 springMVC+Spring+Mybatis+solrJ;
    (2)将 mysql 中的 tb_item 表中的部分业务数据导入到 solr 的索引库中;
    (3) 提供一个搜索页面,在搜索页面中完成数据搜索 ;

    1.数据库创建:

    CREATE TABLE `tb_item` (
      `id` bigint(20) NOT NULL COMMENT '商品id,同时也是商品编号',
      `title` varchar(100) NOT NULL COMMENT '商品标题',
      `sell_point` varchar(500) DEFAULT NULL COMMENT '商品卖点',
      `price` bigint(20) NOT NULL COMMENT '商品价格,单位为:分',
      `num` int(10) NOT NULL COMMENT '库存数量',
      `barcode` varchar(30) DEFAULT NULL COMMENT '商品条形码',
      `image` varchar(500) DEFAULT NULL COMMENT '商品图片',
      `cid` bigint(10) NOT NULL COMMENT '所属类目,叶子类目',
      `status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '商品状态,1-正常,2-下架,3-删除',
      `created` datetime NOT NULL COMMENT '创建时间',
      `updated` datetime NOT NULL COMMENT '更新时间',
      PRIMARY KEY (`id`),
      KEY `cid` (`cid`),
      KEY `status` (`status`),
      KEY `updated` (`updated`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品表';
    
    
    示例

    2.创建父项目(pom):

    • 修改POM文件添加依赖:
        <!-- 对依赖的jar包的版本统一进行定义 -->
        <properties>
            <redis.solr-solrj>4.10.3</redis.solr-solrj>
            <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>
            <commons-fileupload.version>1.3.1</commons-fileupload.version>
            <commons-net.version>3.3</commons-net.version>
            <jackson.version>2.4.2</jackson.version>
            <redis.clients>2.9.0</redis.clients>
        </properties>
    
    
        <!-- jar包的依赖注入 ,由于该工程是一个父工程,所以jar包在该pom文件中只是声明 -->
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.apache.solr</groupId>
                    <artifactId>solr-solrj</artifactId>
                    <version>${redis.solr-solrj}</version>
                </dependency>
                <dependency>
                    <groupId>redis.clients</groupId>
                    <artifactId>jedis</artifactId>
                    <version>${redis.clients}</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>
                <!-- dubbo -->
                <dependency>
                    <groupId>com.alibaba</groupId>
                    <artifactId>dubbo</artifactId>
                    <version>${dubbo-version}</version>
                </dependency>
                <dependency>
                    <groupId>com.101tec</groupId>
                    <artifactId>zkclient</artifactId>
                    <version>${zkClient-version}</version>
                </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>
    
    • 继承parent父项目:


      示例
    • 修改POM文件添加依赖:
        <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项目,所以该插件只是声明,并未开启 -->
            <pluginManagement>
                <plugins>
                    <!-- 配置Tomcat插件 -->
                    <plugin>
                        <groupId>org.apache.tomcat.maven</groupId>
                        <artifactId>tomcat7-maven-plugin</artifactId>
                        <configuration>
                            <path>/</path>
                            <port>8080</port>
                        </configuration>
                    </plugin>
                </plugins>
            </pluginManagement>
        </build>
    
    • 项目框架结构:


      结构
    • applicationContext-mybatis配置文件:
            <!-- 配置解析properties文件的工具类 -->
            <context:property-placeholder location="classpath:resources/*.properties"/>
            
            <!-- 配置数据源dataSource -->
            <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
                <property name="driverClassName" value="${jdbc.driver}" /> 
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" /> 
                <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.zlw.mapper"></property>
            </bean>
    
    • applicationContext-Service:
            <!-- 扫描bean对象 -->
            <context:component-scan base-package="com.zlw.service,com.zlw.dao"/>
    
    • applicationContext-trans:
        <!-- 配置事务管理器的切面 -->
        <bean id="transactionMananger"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </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.zlw.service.impl*.*(..))" />
        </aop:config>
    
    • springmvc:
                <!-- 扫描@Controller -->
                <context:component-scan base-package="com.zlw.web.controller"></context:component-scan>
                
                <!-- 注册两个新对象 主要是为了来处理springmvc 中的其他 anntation 如:@requestmapping  -->
                <mvc:annotation-driven></mvc:annotation-driven>
                <!-- 视图解析器 -->
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/jsp/"></property>
                    <property name="suffix" value=".jsp"></property>
                </bean>
                
                <!-- 配置静态资源映射 -->
                <mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
                <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
    
    • db.properties:
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssm
    jdbc.username=root
    jdbc.password=root
    
    • resource.properties:
    SOLR_SERVICE_URL=http://192.168.226.130:8080/solr
    SOLR_CLOUD_SERVICE_URL=192.168.226.130:2181,192.168.226.130:2182,192.168.226.130:2183
    DEFAULT_COLLECTION=collection2
    
    • spring整合SolrJ

    创建applicationContext-solrJ.xml;

    <?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 id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
            <constructor-arg name="baseURL">
                <value>${}</value>
            </constructor-arg>
        </bean>-->
        
        <!-- 整合solr集群 -->
        <bean 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>
    

    3.将tb_item表中的数据导入Solr的索引库中:

    • 创建实体类:
        private long id;
        private String title;
        private String sell_point;
        private Long price;
        private int num;
        private String barcode;
        private String image;
        private long cid;
        private int status;
        private String datetime;
        private String update;
    
    • 创建导入数据的Service:
    package com.zlw.service.impl;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.solr.client.solrj.SolrServerException;
    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 com.zlw.mapper.ItemMapper;
    import com.zlw.pojo.Tbitem;
    import com.zlw.service.ImportItemService;
    
    @Service
    public class ImportItemServiceImpl implements ImportItemService {
        @Autowired
        private ItemMapper ItemMapper;
    
        @Autowired
        private CloudSolrServer cloudSolrServer;
        @Override
        public void importItem() {
            try {
                //查询数据库
                List<Tbitem> list = ItemMapper.findAll();
                List<SolrInputDocument> arrayList = new ArrayList<>();
                //模型转换
                for (Tbitem tbitem : list) {
                    SolrInputDocument document = new SolrInputDocument();
                    document.addField("id",tbitem.getId()+"");
                    document.addField("item_title", tbitem.getTitle());
                    document.addField("item_sell_point", tbitem.getSell_point());
                    document.addField("item_price", tbitem.getPrice());
                    document.addField("item_image",tbitem.getImage());
                    arrayList.add(document);
                }
                cloudSolrServer.add(arrayList);
                cloudSolrServer.commit();
            } catch (SolrServerException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 创建Controller:
    @Controller
    @RequestMapping("/import")
    public class ImportController {
        @Autowired
        private ImportItemService importItemService;
        @RequestMapping("/data")
        public String importData() {
            importItemService.importItem();
            return "index";
        }
    }
    
    • 实现效果:


      示例

    4.实现搜索业务:

    • 创建SolrDao:
    @Repository
    public class SolrDaoImpl implements SolrDao {
    
        @Autowired
        private CloudSolrServer cloudSolrServer;
    
        @Override
        public PageResult searchItem(SolrQuery solrQuery) throws Exception {
            QueryResponse res = this.cloudSolrServer.query(solrQuery);
            SolrDocumentList list = res.getResults();
            // 处理结果集
            PageResult page = new PageResult();
            // 总条数
            page.setTotalNum(list.getNumFound());
            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.setImage((String) var.get("item_image"));
                item.setSell_point((String) var.get("item_sell_point"));
                item.setPrice((Long)var.get("item_price"));
                List<String> h = hl.get(var.get("id")).get("item_title");
                String 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;
        }
    }
    
    • 创建搜索的Service:
    @Service
    public class SearchItemServiceImpl implements SearchItemService {
    
        @Autowired
        private SolrDao solrDao;
    
        @Override
        public PageResult searchItem(String query, Integer page, Integer rows) throws Exception {
            //创建查询条件 
              SolrQuery solrQuery = new SolrQuery(); 
              //添加查询条件 
              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>"); 
              //调用 SolrDao 
              PageResult result =this.solrDao.searchItem(solrQuery); 
              //补齐数据 
              //当前页 
              result.setPageIndex(page); 
              //总页数 
              Long total = result.getTotalNum()/rows; 
              if(result.getTotalNum() % rows > 0){ 
               total++; 
              } 
              result.setTotalPage(total); 
              return result; 
             }
    }
    
    • 创建搜索的Controller:
    @Controller
    @RequestMapping("/search")
    public class SearchItem {
    
        @Autowired
        private SearchItemService searchItemService;
    
        @RequestMapping("searchItem")
        public String search(String query,@RequestParam(value="page",defaultValue="1")Integer page, @RequestParam(value="rows",defaultValue="20")Integer rows,Model model) {
            
            try {
                PageResult re = searchItemService.searchItem(query, page, rows);
                System.out.println(query+"---"+page+"----"+rows);
                System.out.println(re);
                model.addAttribute("re",re);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "show";
        }
    }
    
    • 创建搜索和数据展示页面:
    
    <form action="/search/searchItem" method="post">
        <p>
            <input type="text" name="query" />
        </p>
        <p>
            <input type="submit" value="搜索" />
        </p>
    </form>
    
    
    <body>
        <table align="center" border="1px">
            <c:forEach items="${re.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>
        <span>当前页:${re.pageIndex }</span>
        <span>总页数:${re.totalPage }</span>
        <span>总条数:${re.totalNum }</span>
    </body>
    
    • 实现效果:


      示例
    示例

    相关文章

      网友评论

          本文标题:Java高级技术day82:solr集群

          本文链接:https://www.haomeiwen.com/subject/lgcdictx.html