Java, Spring
Java 코드로 보는 Connection 관련 timeout 에러 정리
ted k
2023. 3. 1. 17:09
Connection timeout
- handshake 시도 중 서버로부터 응답이 없어서 연결 시간이 초과됨
- 서버와의 handshake 과정에서 연결이 성립되지 않은 경우라고 볼 수 있다.
@Test
void ConnectionTimeOut() throws IOException {
Socket socket = new Socket();
SocketAddress unavailableHost = new InetSocketAddress("3.3.3.3", 99);
socket.connect(unavailableHost, (int) Duration.ofMillis(1000).toSeconds());
}
1초 동안 연결을 시도하고, 연결이 되지 않는다면 위와 같이 Connection timeout 에러를 확일할 수 있다.
Request timeout
- handshake는 됐으나, request가 없는 Connection 에 대해 연결 끊음
- 보안이나 자원 관리 차원에서 서버에서 연결을 끊음
- 사례
- connection pool 로부터 connection 을 대여하기 까지의 timeout
- connection 을 요청한 뒤, 일정 시간이 지나도 connection 을 받지 못했을 경우
- max total connection 이나 max route 가 적은 경우
- max total connection
- connection pool 이 가질 수 있는 최대 connection
- max route
- 동일한 endpoint로 동시에 요청할 수 있는 최대 connection 수
- 동일한 endpoint로 동시에 요청할 수 있는 최대 connection 수
- max total connection
Read timeout
- 클라이언트가 서버와 connection은 성공했지만 I/O 과정이 길어지는 경우 일정 시간이 경과되면 클라이언트는 connection을 끊게 된다.
- Socket timeout과 비슷한 느낌이다.
@GetMapping("/")
public String readTimeOut(HttpServletResponse response) throws InterruptedException {
Thread.sleep(10000000);
return "hi";
}
- 컨트롤러에서는 이후 보게될 timout 기준 시간을 넘겨 sleep 을 수행한다.
- 따라서 write 하는 게 없다.
@Test
public void readTimeout() {
try {
Socket socket = new Socket("localhost", 8080);
socket.setSoTimeout(100); // 100ms 동안 응답이 없으면 read timeout 예외 발생
InputStream input = socket.getInputStream();
byte[] buffer = new byte[1024];
int readBytes = 0;
while ((readBytes = input.read(buffer)) != -1) {
// 읽은 데이터 처리
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
- 100ms 동안 응답이 없으면 read timeout 예외가 발생하도록 설정하였다.
- 위에서 보았듯이, write 하지 않을 예정이므로 아래와 같은 예외가 발생한다.
Socket timeout
- packet 사이의 시간 간격에 대한 timeout
- packet 간 일정 시간이 벌어지게 되면 발생한다.