생계유지형 개발자/Elasticsearch

[Elasticsearch in java] client는 언제 close해 주어야 할까?

이 가을 2020. 7. 24. 15:12

Java로 Elasticsearch에 접근로그 데이터를 저장 및 검색하는 기능을 개발했다.

사용자 유입이 많은 서비스라 하루에도 150만 건 정도의 접근로그가 저장되고 있었다.

Elasticsearch에 연동하기 위해 두 개의 TransportClient 타입의 Client 객체를 생성했다.

하나는 접근로그 저장을 위한 clientForWrite, 또 하나는 검색을 위한 clientForSearch이다.

여기서 의문이 생겼다.

 

Client는 언제 생성하고, 언제 닫아주어야 할까?

 

사용 빈도가 크지 않은 반면 JVM을 비롯한 리소스 관리가 필요한 상황이라면 작업이 필요할 때만 client를 생성하고 작업이 끝나면 닫아주면(close() 메소드 호출) 되겠지만, 접근로그 데이터가 거의 실시간으로 발생하기 때문에 열고 닫는 것이 의미가 있나 싶었다.

그렇다면 서버가 구동될 때 client 생성 및 Elasticsearch에 연동시키고, 서버를 내릴 때 닫아줄 수 있겠지만, 근데 그래도 되나? 싶었다.

왜 그...

JDBC Driver로 연동할 때는 try, catch, final 구문 써서 작업 끝나면 final 안에서 close() 해주는 것처럼 말이다.

JDBC 연동은 소켓을 항상 열어두진 않으니까.

 

구글에서 내가 궁금했던 것과 비슷한 내용의 질문과 그에 대한 답변을 찾았다.

 

Q: I want to know: do we have to call node.close() every time when we are done with our querying/searching process or just client.close() is fine? I am running this code frequently; so, after node.close(), the next time I execute this code, it starts up the node again (causing delays in search response), which is not desired. I want to know if node.close() is the right thing to do when we need to call this searching code frequently.

quering/searching process 처리할때마다 node.close()를 해줘야 할까, 아니면 client.close()만 해주어도 괜찮을까? 

A: In short: no, you can reuse the same client over time without trouble. close() should be used on shutdown only.
Moreover, frequently starting and stopping one or more node clients creates unnecessary noise across the cluster.
Note that using nodeBuilder().client(true).node(), you are creating a node, that will join the ES cluster.
If you just want a client and not a node, you should use TransportClient (https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/transport-client.html).

▶ 같은 client를 문제 없이 재사용할 수 있고 close()는 shutdown(서버 내릴) 때만 사용되어야 해.

Q: do we also don't need to close the client as well?

▶ client도 close할 필요가 없을까? 

A: Yes same thing as node client

▶ 웅, node랑 똑같아.

 

다른 결과들을 더 찾아봐야겠지만 우선은 아주 불가능한 것은 아닌 것으로 생각해도 될 것 같다.