Apache Solr学习 第六篇 Springboot集成solr

一.  构建springboot项目

  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>

    <groupId>com.example</groupId>
    <artifactId>demo-solr</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-solr</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
            <version>6.6.5</version>
        </dependency>
    </dependencies>
</project>

application.yml

server:
  port: 8082
  servlet:
    context-path: /
spring:
  data:
    solr:
      host: http://127.0.0.1:8983/solr
  devtools:
    restart:
      enabled: true
      additional-paths: src/main/java
      exclude: WEB-INF/**

二. 集成swagger

 配置swagger

package com.fan.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
       return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.fan.controller")).paths(PathSelectors.any()).build();
    }
    @Bean
    public ApiInfo apiInfo() {
       return new ApiInfoBuilder().title("solrApi").description("测试").version("1.0").contact(new Contact("","","")).build();
    }
}

三. 实现增删改查

   构建实体类:

package com.fan.pojo;

import org.apache.solr.client.solrj.beans.Field;
import org.springframework.data.annotation.Id;

import java.io.Serializable;

public class Goods implements Serializable {
    @Override
    public String toString() {
        return "Goods{" +
                "id='" + id + '\'' +
                ", goodsname='" + goodsname + '\'' +
                ", price=" + price +
                ", description='" + description + '\'' +
                '}';
    }

    @Id
    private String id;
    @Field("goodsname")
    private String goodsname;
    @Field("price")
    private float price;
    @Field("description")
    private String description;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getGoodsname() {
        return goodsname;
    }

    public void setGoodsname(String goodsname) {
        this.goodsname = goodsname;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

controller层

package com.fan.controller;

import com.fan.pojo.Goods;
import com.fan.services.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/search")
public class SearchController {

    @Autowired
    SearchService searchService;


    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    public  List<Goods> getList(
            @RequestParam(value = "pageNow", required = false, defaultValue = "0") int pageNow,
            @RequestParam(value = "pageSize", required = false, defaultValue = "15") int pageSize) {
         return  this.searchService.queryList(pageNow, pageSize);
    }
    @RequestMapping(value = "/addGoods", method = RequestMethod.POST)
    public Map<String, Object> addGoods(Goods goods) {
          String uuid = searchService.add(goods);
          Map<String, Object> map = new HashMap<>();
          map.put("uuid", uuid);
          return map;
    }
    @RequestMapping(value = "/delGoods", method = RequestMethod.DELETE)
    public void delGoods(String id) {
          searchService.delete(id);
    }
}

service层

package com.fan.services;

import com.fan.pojo.Goods;

import java.util.List;

public interface SearchService {
    String add(Goods goods);

    String delete(String id);

    List<Goods> queryList(int pageNow, int pageSize);
}
package com.fan.services.impl;

import com.fan.pojo.Goods;
import com.fan.services.SearchService;
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.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    SolrClient solrClient;

    @Override
    public String add(Goods goods) {
        SolrInputDocument solrInputDocument = new SolrInputDocument();
        if(goods.getId() == null || "".equals(goods.getId())) {
            goods.setId(UUID.randomUUID().toString().replaceAll("-",""));
        }
        solrInputDocument.setField("id", goods.getId());
        solrInputDocument.setField("goodsname", goods.getGoodsname());
        solrInputDocument.setField("price", goods.getPrice());
        solrInputDocument.setField("description", goods.getDescription());
        try {
            UpdateResponse  updateResponse = solrClient.add("goods_core", solrInputDocument); //操作一定要指定core
            solrClient.commit("goods_core");
            return updateResponse.toString();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public String delete(String id) {
        try {
            UpdateResponse updateResponse = solrClient.deleteById("goods_core",id);
            solrClient.commit("goods_core");
            return updateResponse.toString();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public List<Goods> queryList(int pageNow, int pageSize) {

        List<Goods> goodsList = new ArrayList<>();
        SolrQuery queryParam = new SolrQuery();
        queryParam.set("q","*:*"); //全部查询
        //queryParam.set("q","goodsname:*");  //设置相关查询字段
        queryParam.addFilterQuery("goodsname:手机"); //fq 设置过滤字段
        queryParam.addFilterQuery("price:[1 TO 10000]");  //fq 设置价格过滤
        queryParam.addSort("price", SolrQuery.ORDER.desc);  //设置排序,根据price
        queryParam.setStart(pageNow);  //设置分页
        queryParam.setRows(pageSize);
        /*
         * 高亮设置
         */
        queryParam.setHighlight(true); //开启高亮
        queryParam.addHighlightField("goodsname");  //设置高亮字段
        queryParam.setHighlightSimplePost("<em>");  //设置高亮样式
        queryParam.setHighlightSimplePost("</em>");
        try {
            QueryResponse queryResponse = solrClient.query("goods_core", queryParam);
            queryResponse.getResults().parallelStream().forEach(document -> {
                Goods goods = new Goods();
                goods.setId(document.get("id").toString());
                goods.setGoodsname(document.get("goodsname").toString());
                goods.setPrice((Float) document.get("price"));
                goods.setDescription(document.get("description").toString());
                goodsList.add(goods);
            });
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return goodsList;
    }
}

启动项目,如下图

 

执行测试

增加:

查询

删除

 

以上就是springboot集成solr的全部内容

posted @ 2019-11-25 17:14  哲雪君!  阅读(463)  评论(0编辑  收藏  举报