Skip to content

Commit 114a98e

Browse files
authored
fix: RestTemplate에 연결 및 응답 타임아웃 설정 (#420)
1 parent 7c39756 commit 114a98e

2 files changed

Lines changed: 40 additions & 2 deletions

File tree

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,24 @@
11
package com.roome.global.config;
22

3+
import java.time.Duration;
34
import org.springframework.context.annotation.Bean;
45
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.http.client.SimpleClientHttpRequestFactory;
57
import org.springframework.web.client.RestTemplate;
68

79
@Configuration
810
public class RestTemplateConfig {
911

12+
// 외부 API 호출에 타임아웃 강제
13+
// 타임아웃이 없으면 상대 서버 지연 시 톰캣 스레드가 무한 대기해서 스레드 풀이 고갈되고, 결제 장애가 서비스 전체 장애로 전이될 수 있음
14+
static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3);
15+
static final Duration READ_TIMEOUT = Duration.ofSeconds(10);
16+
1017
@Bean
1118
public RestTemplate restTemplate() {
12-
return new RestTemplate();
19+
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
20+
factory.setConnectTimeout(CONNECT_TIMEOUT);
21+
factory.setReadTimeout(READ_TIMEOUT);
22+
return new RestTemplate(factory);
1323
}
14-
}
24+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.roome.global.config;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.jupiter.api.DisplayName;
6+
import org.junit.jupiter.api.Test;
7+
import org.springframework.http.client.ClientHttpRequestFactory;
8+
import org.springframework.http.client.SimpleClientHttpRequestFactory;
9+
import org.springframework.test.util.ReflectionTestUtils;
10+
import org.springframework.web.client.RestTemplate;
11+
12+
class RestTemplateConfigTest {
13+
14+
@Test
15+
@DisplayName("RestTemplate은 무한 대기를 막기 위해 연결 및 응답 타임아웃이 설정되어 있어야 한다.")
16+
void restTemplate_HasTimeouts() {
17+
// when
18+
RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
19+
ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
20+
21+
// then: 기본(new RestTemplate())이 아닌, 타임아웃이 지정된 팩토리여야 한다
22+
assertThat(factory).isInstanceOf(SimpleClientHttpRequestFactory.class);
23+
assertThat(ReflectionTestUtils.getField(factory, "connectTimeout"))
24+
.isEqualTo((int) RestTemplateConfig.CONNECT_TIMEOUT.toMillis());
25+
assertThat(ReflectionTestUtils.getField(factory, "readTimeout"))
26+
.isEqualTo((int) RestTemplateConfig.READ_TIMEOUT.toMillis());
27+
}
28+
}

0 commit comments

Comments
 (0)