1. 程式人生 > >Maven整合Spring與Solr

Maven整合Spring與Solr

  首先,在maven的pom.xml檔案中配置對spring和solrj客戶端的依賴:

<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>

  <groupId>com.itszt.DemoSS1</groupId>
  <artifactId>DemoSS1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>DemoSS1</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- Spring依賴 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.1.3.RELEASE</version>
    </dependency>

    <!--solr客戶端solrj的依賴 -->
    <dependency>
      <groupId>org.apache.solr</groupId>
      <artifactId>solr-solrj</artifactId>
      <version>4.10.1</version>
    </dependency>

    <!--單元測試-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <!--spring框架整合單元測試-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.1.3.RELEASE</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>  

  配置solr.properties檔案中的solr伺服器資訊:  

solr.Url=http://127.0.0.1:8090/solr/products2
solr.maxRetries=2
solr.connectionTimeout=5000

  配置spring-solr-config.xml檔案中的solrj客戶端資訊:

<?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:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

     <!--定義solr的server-->
     <bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
          <constructor-arg index="0" value="${solr.Url}"/>
          <!-- 設定響應解析器 -->
          <property name="parser">
               <bean class="org.apache.solr.client.solrj.impl.XMLResponseParser"/>
          </property>
          <!-- 設定重試次數-->
          <property name="maxRetries" value="${solr.maxRetries}"/>
          <!-- 建立連線的最長時間 -->
          <property name="connectionTimeout" value="${solr.connectionTimeout}"/>
     </bean>
</beans>  

  配置spring-config.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:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

     <!--整合solr伺服器與客戶端資訊-->
     <context:property-placeholder location="classpath:solr.properties"></context:property-placeholder>
     <import resource="classpath:spring-solr-config.xml"></import>
     
     <!--  為了讓SpringIoC可以基於註解來做,註解支援-->
     <context:annotation-config/>
     <!--指明註解的掃描包,即將來去哪個包裡找註解
     SpringIoC只管掃描service和dao即可
     -->
     <context:component-scan base-package="com.itszt.DemoSS1">
     </context:component-scan>
</beans>

  測試程式碼如下:

package com.itszt.DemoSS1;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
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.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * maven整合spring與solr
 */
@ContextConfiguration(locations = { "classpath:spring-config.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class TestUpdate {
    @Autowired
    HttpSolrServer httpSolrServer;
    @Test
    public void testInsertData() throws IOException, SolrServerException {

        SolrInputDocument solrInputDocument=new SolrInputDocument();
        solrInputDocument.addField("id","10086");
        solrInputDocument.addField("product_price","998");
        solrInputDocument.addField("product_name","大黃音樂");

        httpSolrServer.add(solrInputDocument);
        httpSolrServer.commit();
    }

    @Test
    public void testUpdateData() throws IOException, SolrServerException {

        SolrInputDocument solrInputDocument=new SolrInputDocument();
        solrInputDocument.addField("id","10086");
        solrInputDocument.addField("product_price","998888");
        solrInputDocument.addField("product_name","大黃音樂555");

        httpSolrServer.add(solrInputDocument);
        httpSolrServer.commit();
    }

    @Test
    public void testDelete() throws IOException, SolrServerException {

//        httpSolrServer.deleteById("10086");
        httpSolrServer.deleteByQuery("product:大黃音樂");
         httpSolrServer.commit();

    }
    @Test
    public void testQuery() throws SolrServerException {

        SolrQuery solrQuery=new SolrQuery();
        solrQuery.setQuery("product:掛鉤");
        QueryResponse queryResponse = httpSolrServer.query(solrQuery);

        SolrDocumentList results = queryResponse.getResults();
        for (SolrDocument result : results) {
            Collection<String> fieldNames = result.getFieldNames();
            for (String fieldName : fieldNames) {

                System.out.println(fieldName+"  ---->  "+result.get(fieldName));
            }
        }
    }

    @Test
    public void testQuery2() throws SolrServerException {        SolrQuery solrQuery=new SolrQuery();
        solrQuery.setQuery("product_name:家居");
        solrQuery.setFields("product_name,product_price");
        solrQuery.setFilterQueries("product_price:[10 TO 100]");
        solrQuery.setSort("product_price", SolrQuery.ORDER.asc);
        solrQuery.setHighlight(true);
        solrQuery.set("hl.fl","product_name");
        QueryResponse queryResponse = httpSolrServer.query(solrQuery);

        SolrDocumentList results = queryResponse.getResults();

        System.out.println("查詢回來的數量:"+results.size());
        for (SolrDocument result : results) {
            Collection<String> fieldNames = result.getFieldNames();
            for (String fieldName : fieldNames) {

                System.out.println(fieldName+"  ---->  "+result.get(fieldName));
                System.out.println("------------------------------------");
            }
        }
        //獲取高亮資料:
        System.out.println("獲取高亮資料:");
        Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
        Set<String> set1 = highlighting.keySet();
        for (String key1 : set1) {
            System.out.println("key1---->"+key1);
            Map<String, List<String>> map2 = highlighting.get(key1);
            System.out.println("map2 = " + map2);
            Set<String> set2 = map2.keySet();
            for (String key2 : set2) {
                System.out.println("key2---->"+key2);
            }
        }
    }
}