Springboot 2.3.2 통합elasticsearch 간단한 예

28549 단어 마이크로 서비스

통합 배경


엘크나 빠른 검색은 엘라스틱 검색에 사용되는데, 그의 속도가 매우 빠르기 때문이다.어떻게 최신 인터페이스 집적을 채택할 것인가, 다음은 하나의 예시를 소개한다.

코드 예제


1. 추가 의존

 <properties>
        <java.version>1.8java.version>
        <elastic.version>7.8.0elastic.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-elasticsearchartifactId>
        dependency>





        <dependency>
            <groupId>org.elasticsearch.clientgroupId>
            <artifactId>elasticsearch-rest-high-level-clientartifactId>
            <version>${elastic.version}version>
        dependency>
        <dependency>
            <groupId>org.elasticsearchgroupId>
            <artifactId>elasticsearchartifactId>
            <version>${elastic.version}version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.71version>
        dependency>
    dependencies>

2. 코드 작성 컨트롤러

package vip.mate.elasticsearch.controller;

import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.mate.elasticsearch.entity.User;
import vip.mate.elasticsearch.service.IEsService;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@AllArgsConstructor
public class TestEsController {

    private final IEsService esService;

    @RequestMapping(value = "helloEs")
    public Map<String, Object> hello() {

        Map<String, Object> query = new HashMap<>();
        try{
            User user = User.builder()
                    .id(1L)
                    .name(" ")
                    .desc(" JAVA ")
                    .build();
            String indexId = "test001";
            esService.save(user, indexId);

            User user2 = User.builder()
                    .id(2L)
                    .name(" ")
                    .desc(" ")
                    .build();
            indexId = "test002";
            esService.save(user2, indexId);

            query = esService.query(indexId);
        }catch (IOException e){
            e.printStackTrace();
        }
//        return Result.data(query);
        return query;
    }
}


3. 코드 작성의 entity

package vip.mate.elasticsearch.entity;

import lombok.Builder;
import lombok.Data;

import java.io.Serializable;

@Data
@Builder
public class User implements Serializable {

    private static final long serialVersionUID = 1809041336715990704L;

    private Long id;
    private String name;
    private String desc;
}


4. 코드 작성 서비스

package vip.mate.elasticsearch.service;

import vip.mate.elasticsearch.entity.User;

import java.io.IOException;
import java.util.Map;

public interface IEsService {

    boolean save(User user, String indexId) throws IOException;

    Map<String, Object> query(String indexId) throws IOException;
}


이것은 업무 인터페이스류이다
package vip.mate.elasticsearch.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;
import vip.mate.elasticsearch.entity.User;
import vip.mate.elasticsearch.service.IEsService;

import java.io.IOException;
import java.util.Map;

@Service
@AllArgsConstructor
public class EsServiceImpl implements IEsService {

    private final RestHighLevelClient restHighLevelClient;
    private final String indexName = "indexname";

    @Override
    public boolean save(User user, String indexId) throws IOException {
        String json = JSON.toJSONString(user);
        IndexRequest request = new IndexRequest(indexName).id(indexId).source(json, XContentType.JSON);
        restHighLevelClient.index(request, RequestOptions.DEFAULT);
        return true;
    }

    @Override
    public Map<String, Object> query(String indexId) throws IOException  {
        GetRequest request = new GetRequest(indexName, indexId);
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        return response.getSource();
    }
}


이상 은 업무 실현 유형 이다

5. 공사를 시작하여 테스트를 진행한다


URL 열기:http://localhost:8888/helloEs데이터를 추가하고 질의할 수 있는 DEMO

코드 샘플


https://github.com/735728811/mate-elasticsearch-demo
이상은 가장 간단한 데모일 뿐입니다. 초보자의 학습용으로 편리하고 후속적으로 조작 도구를 통합할 수 있으니 기대해 주십시오.

좋은 웹페이지 즐겨찾기