Springboot整合elasticsearch6.x

環境介紹:
win7系統,es服務器爲6.4.2(原文提供下載地址,廢了好大勁才找到,搜索引擎用的好,確實差不少)

如何快速創建springboot工程
訪問https://start.spring.io/ ,搜索web,springdata,我們使用springdata方式鏈接es

首先給出項目結構圖如下圖所示(啓動項目,訪問對應的url,也可以通過可視化工具查看es數據)

接下來給出項目代碼
controller

    package com.example.demo.controller;
    import com.example.demo.resp.entity.Commodity;
    import com.example.demo.resp.service.CommodityService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    import java.util.List;
    @RestController
    public class ElasticSearchController {
        @Autowired
        private CommodityService commodityService;
        @RequestMapping("/commodity/{name}")
        @ResponseBody
        public List<Commodity> getCommodityByName(@PathVariable String name) {
            List<Commodity> list = commodityService.findByName(name);
            System.out.println(list);
            return list;
        }
    @RequestMapping("/save")
    @ResponseBody
    public void Save() {
        Commodity commodity = new Commodity();
        commodity.setSkuId("1501009001");
        commodity.setName("原味切片面包(10片裝)");
        commodity.setCategory("101");
        commodity.setPrice(880);
        commodity.setBrand("良品鋪子");
        Commodity save1 = commodityService.save(commodity);
        System.out.println(save1.getSkuId() + "==========");
        commodity = new Commodity();
        commodity.setSkuId("1501009002");
        commodity.setName("原味切片面包(6片裝)");
        commodity.setCategory("101");
        commodity.setPrice(680);
        commodity.setBrand("良品鋪子");
        Commodity save2 = commodityService.save(commodity);
        System.out.println(save2.getSkuId() + "==========");
        commodity = new Commodity();
        commodity.setSkuId("1501009004");
        commodity.setName("元氣吐司850g");
        commodity.setCategory("101");
        commodity.setPrice(120);
        commodity.setBrand("百草味");
        Commodity save3 = commodityService.save(commodity);
        System.out.println(save3.getSkuId() + "==========");
    }

    /**
     * 分頁查詢
     */
    @RequestMapping("/pagequery")
    @ResponseBody
    public Page<Commodity> pageQuery() {
        Page<Commodity> pageResult = commodityService.pageQuery(0, 10, "切片");
        return pageResult;
    }
}

repository

package com.example.demo.resp.dao;
import com.example.demo.resp.entity.Commodity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CommodityRepository extends ElasticsearchRepository<Commodity, String> {
    //springdata 幫你實現 對應的query
    // List<Commodity> findByName(String name);
}

entity(getset省略)

@Document(indexName = "commodity")
public class Commodity implements Serializable {
@Id
private String skuId;
private String name;
private String category;
private Integer price;
private String brand;
private Integer stock;

service

package com.example.demo.resp.service;
import com.example.demo.resp.entity.Commodity;
import org.springframework.data.domain.Page;
import java.util.List;
public interface CommodityService {
    long count();
    Commodity save(Commodity commodity);
    void delete(Commodity commodity);
    Iterable<Commodity> getAll();
    List<Commodity> findByName(String name);
    Page<Commodity> pageQuery(Integer pageNo, Integer pageSize, String kw);
}

service實現類

package com.example.demo.resp.service.impl;
import com.example.demo.resp.dao.CommodityRepository;
import com.example.demo.resp.entity.Commodity;
import com.example.demo.resp.service.CommodityService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class CommodityServiceImpl implements CommodityService {
    @Resource
    private CommodityRepository commodityRepository;
    @Override
    public long count() {
        return commodityRepository.count();
    }

    /**
     * 插入向es商品 ,場景可以監聽binlog 通過三方框架,或者mq,及時更新新增商品
     *
     * @param commodity
     * @return
     */
    @Override
    public Commodity save(Commodity commodity) {
        return commodityRepository.save(commodity);
    }

    /**
     * 刪除
     *
     * @param commodity
     */
    @Override
    public void delete(Commodity commodity) {
        commodityRepository.delete(commodity);
    }

    /**
     * 查詢所有商品
     *
     * @return
     */
    @Override
    public Iterable<Commodity> getAll() {
        return commodityRepository.findAll();
    }

    /**
     * @param name
     * @return
     * @Query("{"bool" : {"must" : {"field" : {"name" : "?0"}}}}")  es中查詢方式 爲json格式數據
     */
    @Override
    public List<Commodity> findByName(String name) {
        List<Commodity> list = new ArrayList<>();
        /**
         * 匹配查詢條件  後面如果寫的文章的話 會具體寫查詢條件
         *
         */
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name", name);
        Iterable<Commodity> iterable = commodityRepository.search(matchQueryBuilder);
        iterable.forEach(e -> list.add(e));
        return list;
    }

    /**
     * @param pageNo
     * @param pageSize
     * @param kw
     * @return
     */
    @Override
    public Page<Commodity> pageQuery(Integer pageNo, Integer pageSize, String kw) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchPhraseQuery("name", kw))
                .withPageable(PageRequest.of(pageNo, pageSize))
                .build();
        return commodityRepository.search(searchQuery);
    }
}

config

package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.example.demo.resp.dao")
class Config {

}

啓動類

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

屬性文件(鏈接超時沒有加)

# ELASTICSEARCH (ElasticsearchProperties)
# Elasticsearch cluster name. 集羣名稱
spring.data.elasticsearch.cluster-name=myapplication
# Comma-separated list of cluster node addresses.
#你的ip地址
spring.data.elasticsearch.cluster-nodes=***:9300
# Whether to enable Elasticsearch repositories.
spring.data.elasticsearch.repositories.enabled=true

pom文件

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-elasticsearch -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

項目數據如下

在這裏插入圖片描述
在這裏插入圖片描述
集成es遇到的問題
在這裏插入圖片描述

解決問題,主要是es的yml文件對應修改幾個參數位置
在這裏插入圖片描述

爲什麼沒有用官方最高7.2版本的​es?多次啓動閃退​?
​因爲springdata版本不匹配,會報一個錯誤,低版本的springboot鏈接高版本的es,es版本號爲7.2,從報錯來看,也說明學習netty的重要性​。

多次閃退解決辦法,修改yml文件的nodes註釋
在這裏插入圖片描述
註解去掉,就不閃退了​。
在這裏插入圖片描述
給出es6.x版本下載地址(網速可能非常慢,原文給出jar包)
https://www.elastic.co/cn/downloads/past-releases/elasticsearch-6-6-0

通過springdata可以快速使用es,而不用瞭解es搜索的語法,springdata​幫我們封裝了。代碼同關係數據庫是一樣的原理。

在這裏插入圖片描述

總結​:文章一直沒發出來就是因爲使用es版本過高,導致報錯,其實如果你確實想用最新的es,可以自己springdata源碼 ,自己打jar包去依賴,給出如下地址,感謝閱讀​。
https://github.com/spring-projects/spring-data-elasticsearch

參考博文鏈接:
https://blog.csdn.net/chengyuqiang/article/details/86135795
https://www.cnblogs.com/cjsblog/p/9756978.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章