Java

[소스 까보기] AsyncRestTemplate 편

SH.DevBlog 2023. 10. 22. 18:49
AsyncRestTemplate 사용 이유?
  • API 통신할 때, 비동기로 빠르게 통신하여 성능을 개선하는 경우에 성능 튜닝을 목적으로 사용한다.
    ex) 알림톡 중계서버에 API로 알림 내역을 전송시 활용

AsyncRestTemplate 핵심 내용
  • 디버깅하여 소스를 깊게 들어가보면 아래와 같은 로직을 볼 수 있다. 주목할 점은 저 submitListenable 메소드가 핵심 역할이다.
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(
        HttpHeaders headers, byte[] bufferedOutput) throws IOException {

    return this.taskExecutor.submitListenable(() -> {
        SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
        // JDK <1.8 doesn't support getOutputStream with HTTP DELETE
        if (getMethod() == HttpMethod.DELETE && bufferedOutput.length == 0) {
            this.connection.setDoOutput(false);
        }
        if (this.connection.getDoOutput() && this.outputStreaming) {
            this.connection.setFixedLengthStreamingMode(bufferedOutput.length);
        }
        this.connection.connect();
        if (this.connection.getDoOutput()) {
            FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream());
        }
        else {
            // Immediately trigger the request in a no-output scenario as well
            this.connection.getResponseCode();
        }
        return new SimpleClientHttpResponse(this.connection);
    });
}
  • 왜냐하면 아래와 같이 Runnable이라는 함수형 인터페이스를 파라미터로 받고 submitListenable 내부의 메소드가 호출되기 때문이다.
@Override
public ListenableFuture<?> submitListenable(Runnable task) {
    ListenableFutureTask<Object> future = new ListenableFutureTask<>(task, null);
    execute(future, TIMEOUT_INDEFINITE);
    return future;
}
  • 그리고 더 Deep 하게 들어가면 결국은 Thread를 생성하거나 ThreadFactory에서 가져와 처리하는 것을 볼 수 있다. Thread.start()가 호출되면 Runnable내부의 task가 실행된다. 통신 방식은 HttpURLConnection을 활용하였다.
protected void doExecute(Runnable task) {
    Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));
    thread.start();
}

결론

  • AsyncRestTemplate은 Runnable 함수형 인터페이스, Thread, HttpURLConnection 이 세 가지를 활용하여 비동기 API 통신을 구현하였다.