본문 바로가기

Programming!

Local Docker Elasticsearch 운영 - Spring + High Level Client

이전에 설치했던 elasticsearch 가 잘 운영되고 있다면..


http://127.0.0.1:9200/_cat/health

1545724265 07:51:05 docker-cluster green 2 2 10 5 0 0 0 0 - 100.0%



스프링부트로 새로운 프로젝트를 생상한다.

IDEA 도움을 받아 프로젝트 설치 후, build.gradle 파일을 열어보자

buildscript {

ext {

springBootVersion = '2.1.1.RELEASE'

}

repositories {

mavenCentral()

}

dependencies {

classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")

}

}


apply plugin: 'java'

apply plugin: 'eclipse'

apply plugin: 'org.springframework.boot'

apply plugin: 'io.spring.dependency-management'


group = 'com.example'

version = '0.0.1-SNAPSHOT'

sourceCompatibility = 1.8


repositories {

mavenCentral()

}



dependencies {

    //implementation('org.springframework.boot:spring-boot-starter-data-elasticsearch')

    compile('org.elasticsearch.client:elasticsearch-rest-client:6.5.4')

    compile('org.elasticsearch.client:elasticsearch-rest-high-level-client:6.5.4')

    compile('com.google.guava:guava:27.0.1-jre')

    

    

    compile('org.springframework.boot:spring-boot-starter-web')

    compile('org.springframework.boot:spring-boot-configuration-processor')

    compile('org.projectlombok:lombok')

    testImplementation('org.springframework.boot:spring-boot-starter-test')

}


기본적으로 elasticsearch를 지정하면 spring-data 버전이 따라오는데, elasticsearch를 저장소 개념으로 사용한다면 data를 사용해도 되지만 단순히 검색을 사용하는 것이라 개인적인 선호도를 반영해 high level client를 사용하게 되었다.


elasticsearch hlc를 사용하기 위한 설정 코드를 작성한다.

@Configuration

public class ElasticSearchConfiguration {

private static final String HTTP_SCHEME = "http";


@Value("#{'${elasticsearch.hosts}'.split(',')}")

private List<String> esHosts;

@Value("${elasticsearch.port:9200}")

private int port;


@Bean(name = "esObjectMapper")

public ObjectMapper esObjectMapper() {

return new ObjectMapper();

}


@Bean(name = "esRestClientBuilder")

public RestClientBuilder esRestClientBuilder() {

HttpHost[] hosts = esHosts.stream().map(this::makeHttpHost).filter(Objects::nonNull).toArray(HttpHost[]::new);

return RestClient.builder(hosts);

}


@Bean(name = "esHighLevelClient", destroyMethod = "close")

public RestHighLevelClient highLevelClient(@Autowired @Qualifier("esRestClientBuilder") RestClientBuilder esRestClientBuilder) {

esRestClientBuilder.setMaxRetryTimeoutMillis(3000);

return new RestHighLevelClient(esRestClientBuilder);

}


private HttpHost makeHttpHost(String ip) {

return new HttpHost(ip, port, HTTP_SCHEME);

}

}


작성중...