아무거나

[Spring Boot] elasticsearch 5.x 사용(transportClient) 본문

Java/Spring

[Spring Boot] elasticsearch 5.x 사용(transportClient)

전봉근 2019. 8. 23. 13:17
반응형

[springboot] elasticsearch 5.x 사용(transportClient)

 

 

    elasticsearch는 자바로 개발되었다. 그래서 9300 포트는 자바 네이티브로 API개발이 가능하다.

자바 관점에서 API 분류

 - 자바 네이티브 API - TransportClient, NodeClient

         - HTTP Rest API - restTemplate/Apache HttpClient와 같은 툴로 직접 연결, Jest     

 

 

**** 해당 내용은 NodeClient와 TransportClient로 개발이 쉽게 가능하다는 장점이 있다. 그러나 공식적으로 쓰지 않기를 권고 하고 있다. 

     기능이 추가되어 버전이 올라갈 때 모델이 바뀌고 있다는 점을 현재 강조하고 있으며, 9200포트를 이용하여 REST API로 개발하기를 권고하고 있다. 

     또한, 일래스틱서치 클러스터의 노드로 연동되기 때문에 일래스틱서치의 로그를 계속 받도록 되어 있다.

     예를 들면, 아래와 같은 로그를 일래스틱서치 클라이언트도 받는다. 

     -> 2015-08-18 15:02:22.839  INFO 27145 --- [anagement][T#2]] o.e.cluster.routing.allocation.decider : 

        [Unseen] high disk watermark exceeded on one or more nodes, rerouting shards

        2015-08-18 15:02:52.825  WARN 27145 --- [anagement][T#2]] o.e.cluster.routing.allocation.decider : 

[Unseen] high disk watermark [10%] exceeded on [5kXkv-RfQEumsEqOsTUaKA][Unseen] free: 15.2gb[6.5%], shards will be relocated away from this node 

 

     ----> transportClient의 개발이 아닐경우는 다른 게시글을 참고하자. 

 

 

 

1. 메뉴얼 주소(https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/index.html)

 

2. 레파지토리 주소(https://mvnrepository.com/artifact/org.elasticsearch.client/transport/5.5.0)

 

3. application.yml 추가

   [application.yml]

....
  elasticsearch:
    cluster-name: {클러스터명}
    host: 127.0.0.1
    port: 9300
....

 

4. build.gradle 추가

[build.gradle]
dependencies {
    ...

    // elasticsearch
    compile('org.elasticsearch:elasticsearch:5.5.0')
    compile('org.elasticsearch.client:transport:5.5.0')
    compile('org.apache.logging.log4j:log4j-to-slf4j:2.7')

    ....
}

    * log4j는 elasticsearch가 자체 로깅을 하기 위해서 필요

 

5. 설정파일 생성

   [ESconfig.java]

@Configuration
public class EsConfig {

    @Value("${elasticsearch.cluster-name}")
    private String clusterName;

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private int port;

    @Bean
    public Client client() throws Exception {
        Settings settings = Settings.builder()
        .put("cluster.name", clusterName).build();

        return new PreBuiltTransportClient(settings)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
    }
    
}

 

6. Repository 생성

   [EsRepository.java]

@Repository
public class EsRepository {

    private Client client;

    @Autowired
    public EsRepository(Client client) {
        this.client = client;
    }

    public HashMap<String, Object> findSongWithPrefix(String prefix) {
        SearchResponse response = client.prepareSearch("meta")
            .setTypes("song")
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setQuery(QueryBuilders.prefixQuery("name", prefix))
            .setFrom(0).setSize(20).setExplain(true)
            .get();

        SearchHits hits = response.getHits();

        HashMap<String ,Object> result = new HashMap<>();

        result.put("total", hits.getTotalHits());
        result.put("contentsList", hits.getHits());

        return result;
    }

}

 

7. 결과확인

   [test]

@Test
public void test1() {
    HashMap<String, Object> result = esRepository.findSongWithPrefix("시그");

    SearchHit [] hits = (SearchHit [])result.get("contentsList");
    System.out.println("Total : " + result.get("total"));
    System.out.println("Song Name : " + hits[0].getSource().get("name"));
}

 

** 결과

Total : 1

Song Name : 시그널 

반응형
Comments