-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFastApiClient.java
More file actions
127 lines (115 loc) · 5.14 KB
/
FastApiClient.java
File metadata and controls
127 lines (115 loc) · 5.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package DiffLens.back_end.global.fastapi;
import DiffLens.back_end.global.aop.annotations.LogExecutionTime;
import DiffLens.back_end.global.responses.code.status.error.ErrorStatus;
import DiffLens.back_end.global.responses.exception.handler.ErrorHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
/**
* FastAPI 서버에 실제 HTTP 요청을 보냄
*/
@Component
@RequiredArgsConstructor
public class FastApiClient {
private final WebClient fastApiWebClient;
/**
*
* @param type fast api에 보낼 요청을 관리하는 enum - FastApiRequestType
* @param requestBody fast api에 요청 보낼 클래스의 타입
* @return fast api 로부터 응답받은 데이터 ( R )
* @param <T> request body의 클래스
* @param <R> response body의 클래스
*
*/
@LogExecutionTime("서브서버 호출 소요시간")
public <T, R> R sendRequest(FastApiRequestType type, T requestBody) {
// 요청 타입이 맞지 않을 경우에 대한 예외
if (!type.getRequestBody().isInstance(requestBody)) {
throw new IllegalArgumentException("올바르지 않은 요청 타입 " + type.name()); // TODO : 에외처리...
}
R block = null;
try {
block = fastApiWebClient.post()
.uri(type.getUri())
.bodyValue(requestBody)
.retrieve()
.bodyToMono((Class<R>) type.getResponseType())
.block();
} catch (Exception e) { // fast api 호출 중 에러 발생시 예외 발생
throw new ErrorHandler(ErrorStatus.SUB_SERVER_ERROR);
}
return block;
}
/**
* PathVariable을 사용하는 GET 요청
*
* @param type fast api에 보낼 요청을 관리하는 enum - FastApiRequestType
* @param requestBody 요청 본문 (null 가능)
* @param pathVariables URI에 포함될 경로 변수들
* @return fast api 로부터 응답받은 데이터 ( R )
* @param <T> request body의 클래스
* @param <R> response body의 클래스
*/
@LogExecutionTime("서브서버 호출 소요시간")
public <T, R> R sendRequestWithPathVariable(FastApiRequestType type, T requestBody, Object... pathVariables) {
R block = null;
try {
block = fastApiWebClient.get()
.uri(type.getUri(), pathVariables)
.retrieve()
.bodyToMono((Class<R>) type.getResponseType())
.block();
} catch (Exception e) {
throw new ErrorHandler(ErrorStatus.SUB_SERVER_ERROR);
}
return block;
}
/**
* Query Parameter를 사용하는 POST 요청
*
* @param type fast api에 보낼 요청을 관리하는 enum - FastApiRequestType
* @param queryParams 쿼리 파라미터 맵 (key-value 쌍)
* @return fast api 로부터 응답받은 데이터 ( R )
* @param <R> response body의 클래스
*/
@LogExecutionTime("서브서버 호출 소요시간")
public <R> R sendRequestWithQueryParams(FastApiRequestType type, java.util.Map<String, Object> queryParams) {
R block = null;
try {
block = fastApiWebClient.post()
.uri(uriBuilder -> {
var builder = uriBuilder.path(type.getUri());
queryParams.forEach((key, value) -> {
if (value != null) {
builder.queryParam(key, value);
}
});
return builder.build();
})
.retrieve()
.bodyToMono((Class<R>) type.getResponseType())
.block();
} catch (WebClientResponseException e) {
// 서브서버의 실제 응답 상태 코드와 메시지 로깅
System.err.println("=== 서브서버 응답 오류 ===");
System.err.println("URI: " + type.getUri());
System.err.println("Query Params: " + queryParams);
System.err.println("Status Code: " + e.getStatusCode());
System.err.println("Response Body: " + e.getResponseBodyAsString());
System.err.println("Error Message: " + e.getMessage());
e.printStackTrace();
throw new ErrorHandler(ErrorStatus.SUB_SERVER_ERROR);
} catch (Exception e) {
// 기타 예외 (네트워크 오류, 타임아웃 등)
System.err.println("=== 서브서버 요청 오류 ===");
System.err.println("URI: " + type.getUri());
System.err.println("Query Params: " + queryParams);
System.err.println("Error Type: " + e.getClass().getName());
System.err.println("Error Message: " + e.getMessage());
e.printStackTrace();
throw new ErrorHandler(ErrorStatus.SUB_SERVER_ERROR);
}
return block;
}
}