Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
package com.roome.global.config;

import java.time.Duration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

// 외부 API 호출에 타임아웃 강제
// 타임아웃이 없으면 상대 서버 지연 시 톰캣 스레드가 무한 대기해서 스레드 풀이 고갈되고, 결제 장애가 서비스 전체 장애로 전이될 수 있음
static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3);
static final Duration READ_TIMEOUT = Duration.ofSeconds(10);

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(CONNECT_TIMEOUT);
factory.setReadTimeout(READ_TIMEOUT);
return new RestTemplate(factory);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.roome.global.config;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.RestTemplate;

class RestTemplateConfigTest {

@Test
@DisplayName("RestTemplate은 무한 대기를 막기 위해 연결 및 응답 타임아웃이 설정되어 있어야 한다.")
void restTemplate_HasTimeouts() {
// when
RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
ClientHttpRequestFactory factory = restTemplate.getRequestFactory();

// then: 기본(new RestTemplate())이 아닌, 타임아웃이 지정된 팩토리여야 한다
assertThat(factory).isInstanceOf(SimpleClientHttpRequestFactory.class);
assertThat(ReflectionTestUtils.getField(factory, "connectTimeout"))
.isEqualTo((int) RestTemplateConfig.CONNECT_TIMEOUT.toMillis());
assertThat(ReflectionTestUtils.getField(factory, "readTimeout"))
.isEqualTo((int) RestTemplateConfig.READ_TIMEOUT.toMillis());
}
}
Loading