아무거나 개발공부/스프링 완전 정복

스프링 부트 2.x 에서 3.x 로 버전 업 시 발생하는 이슈

코드 살인마 2023. 11. 29. 22:19
728x90

개요

스프링 부트 2.x 에서 3.x 로 마이그레이션하면서, 여러 이슈가 있었는데, 그 중org.apache.httpcomponents.client5 의존성은 개인적으로 까다롭고, 바뀐 버전에 대해 정확히 알아보고 사용해야 할 것 같아 정리한다.

pom.xml 수정

BEFORE

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

AFTER

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.2.1</version>
</dependency>

RestTemplate

버전 업 이후, RestTemplate설정 부분에서 에러가 발생하였다.

원인은 Spring Framework 6(스프링 부트 3.x)에서 HttpClient 4 라이브러리가 삭제되었기 때문이다.

  • 아래 스프링 공식문서 참고
Dependency Management for Apache HttpClient 4
Support for Apache HttpClient 4 with RestTemplate was removed in Spring Framework 6, in favor of Apache HttpClient 5. Spring Boot 3.0 includes dependency management for both HttpClient 4 and 5. Applications that continue to use HttpClient 4 can experience errors when using RestTemplate that are difficult to diagnose.

Spring Boot 3.1 removes dependency management for HttpClient 4 to encourage users to move to HttpClient 5 instead.


기존 GIA에서는 `RestTemplate`을 커스텀 설정하여 사용 중에 있는데, 2개의 에러가 발생했다.

첫번째 에러

HttpComponentsClientHttpRequestFactory에서 setReadTimeout 옵션이 deprecated


javadoc 참고하여, SocketConfig.Builder.setSoTimeout을 대신 사용하였다.

BEFORE

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

requestFactory.setReadTimeout(5000);

AFTER

SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();

두번째 에러

HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(100).setMaxConnPerRoute(80).build();

형식의 HttpClientBuilder을 지원 안함

 

아파치 공식 문서을 참고하여

HttpClientsPoolingHttpClientConnectionManagerBuilder을 대신 사용였다.

BEFORE

HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(100).setMaxConnPerRoute(80).build();

AFTER

HttpClient httpClient = HttpClients.custom()
	.setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
        .setDefaultSocketConfig(socketConfig)
    	.setMaxConnPerRoute(100)
    	.setMaxConnTotal(80)
    	.build())
    .build();

이 외에도..

다양한 옵션이 존재하는데 공식문서에 굉장히 잘 나와있다. 아파치 공식문서를 적극 활용하자

아파치 공식 문서

 

Apache HttpComponents – HttpClient Overview

<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apa

hc.apache.org