-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
재시도 로직 구현 및 테스트 추가 #7
Merged
+151
−43
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
f670970
DELETE - jvm-sdk/ 코루틴 라이브러리 삭제
Stark-Industries0417 b938674
FEAT - jvm-sdk/ 사용자에게 네트워크 설정 기능 적용
Stark-Industries0417 bc1a912
FEAT - jvm-sdk/ 사용자에게 네트워크 설정 기능 적용
Stark-Industries0417 0f2f5cd
FEAT - jvm-sdk/ OkHttpClient http request 비동기 호출
Stark-Industries0417 078981b
FEAT - jvm-sdk/ 네트워크 요청 실패 시 재시도 로직 개발
Stark-Industries0417 01a9ce3
UPDATE - jvm-sdk/ 네트워크 config 동시성 이슈로 객체 프로퍼티 불변으로 변경
Stark-Industries0417 b67c54e
FEAT - jvm-sdk/ 재시도 로직 및 테스트 기능 개발
Stark-Industries0417 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
110 changes: 70 additions & 40 deletions
110
jvm-sdk/src/main/kotlin/com/gamedatahub/network/JvmNetworkClient.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,62 +1,92 @@ | ||
package com.gamedatahub.network | ||
|
||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.launch | ||
import com.fasterxml.jackson.databind.ObjectMapper | ||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory | ||
import com.fasterxml.jackson.module.kotlin.KotlinModule | ||
import okhttp3.MediaType.Companion.toMediaType | ||
import okhttp3.OkHttpClient | ||
import okhttp3.Request | ||
import kotlinx.coroutines.suspendCancellableCoroutine | ||
import okhttp3.* | ||
import okhttp3.RequestBody.Companion.toRequestBody | ||
import java.io.File | ||
import java.io.IOException | ||
import kotlin.coroutines.resume | ||
import kotlin.coroutines.resumeWithException | ||
|
||
class JvmNetworkClient( | ||
private val client: OkHttpClient = OkHttpClient() | ||
data class NetworkClientConfig( | ||
val isRetryEnabled: Boolean = false, | ||
val maxRetries: Int = 1, | ||
val retryDelayMillis: Long = 1000, | ||
val backoffFactor: Double = 2.0 | ||
) | ||
|
||
class JvmNetworkClient private constructor( | ||
private val client: OkHttpClient, | ||
val config: NetworkClientConfig, | ||
) : NetworkClient { | ||
private val scope = CoroutineScope(Dispatchers.IO) | ||
|
||
override fun postDataAsync(url: String, data: String) { | ||
scope.launch { | ||
try { | ||
val response = client.makePostRequest(url, data) | ||
TODO("성공 핸들링") | ||
} catch (e: Exception) { | ||
TODO("실패 핸들링") | ||
} | ||
} | ||
client.makePostRequestAsync(url, data) | ||
} | ||
} | ||
|
||
private suspend fun OkHttpClient.makePostRequest(url: String, data: String): String { | ||
val requestBody = data.toRequestBody("application/json".toMediaType()) | ||
val request = Request.Builder() | ||
.url(url) | ||
.post(requestBody) | ||
.build() | ||
|
||
return suspendCancellableCoroutine { continuation -> | ||
val call = this.newCall(request) | ||
|
||
call.enqueue(object : Callback { | ||
override fun onResponse(call: Call, response: Response) { | ||
if (response.isSuccessful) { | ||
continuation.resume(response.body?.string() ?: "") | ||
|
||
private fun OkHttpClient.makePostRequestAsync( | ||
url: String, | ||
data: String, | ||
attempt: Int = 0 | ||
) { | ||
val requestBody = data.toRequestBody("application/json".toMediaType()) | ||
val request = Request.Builder() | ||
.url(url) | ||
.post(requestBody) | ||
.build() | ||
|
||
val maxAttempts = config.maxRetries | ||
var delay = config.retryDelayMillis | ||
|
||
this.newCall(request).enqueue(object : okhttp3.Callback { | ||
override fun onFailure(call: okhttp3.Call, e: IOException) { | ||
var tmpAttempt = attempt | ||
tmpAttempt++ | ||
if (tmpAttempt <= maxAttempts && config.isRetryEnabled) { | ||
Thread.sleep(delay) | ||
delay = (delay * config.backoffFactor).toLong() | ||
makePostRequestAsync(url, data, tmpAttempt) | ||
} else { | ||
continuation.resumeWithException(Exception("Error: ${response.code} - ${response.message}")) | ||
println("Request failed after ${tmpAttempt} attempts: ${e.message}") | ||
} | ||
response.close() | ||
} | ||
|
||
override fun onFailure(call: Call, e: IOException) { | ||
continuation.resumeWithException(e) | ||
override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) { | ||
response.use { | ||
if (!response.isSuccessful) | ||
onFailure(call, IOException("HTTP ${response.code}: ${response.message}")) | ||
} | ||
} | ||
}) | ||
} | ||
|
||
class Builder { | ||
private var client: OkHttpClient = OkHttpClient() | ||
private var config: NetworkClientConfig = NetworkClientConfig() | ||
|
||
private val yamlMapper: ObjectMapper = ObjectMapper(YAMLFactory()) | ||
.registerModule(KotlinModule()) | ||
|
||
fun loadFromYaml(filePath: String = "config.yml") = | ||
apply { | ||
val file = File(filePath) | ||
config = if (!file.exists()) { | ||
NetworkClientConfig() | ||
} else { | ||
yamlMapper.readValue(file, NetworkClientConfig::class.java) | ||
} | ||
} | ||
|
||
fun httpClient(client: OkHttpClient) = apply { this.client = client } | ||
fun enableRetry(isEnabled: Boolean) = apply { this.config = this.config.copy(isRetryEnabled = isEnabled) } | ||
fun maxRetries(maxRetries: Int) = apply { this.config = this.config.copy(maxRetries = maxRetries) } | ||
fun retryDelayMillis(delayMillis: Long) = apply { this.config = this.config.copy(retryDelayMillis = delayMillis) } | ||
fun backoffFactor(factor: Double) = apply { this.config = this.config.copy(backoffFactor = factor) } | ||
|
||
continuation.invokeOnCancellation { | ||
call.cancel() | ||
fun build(): JvmNetworkClient { | ||
return JvmNetworkClient(client, config) | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
재시도 로직은 좋은 것 같은데요. 음 ... 만약 재시도를 해야하는 상황이라면, 요청을 받는 서버쪽에 문제가 생겼을 가능성이 높은데, 그 타이밍에 계속 재시도를 하는 것이 좋은가? 에 대해서 생각해보면, 좋을 것 같네요. (이 문제는 답은 없습니다만...) 그리고 재시도 하는 동안 (정확히는 sleep하는동안) 요청이 계속 들어올텐데, 그럼 그런 요청들도 문제가 생겨서 재시도 로직을 타게되면, 결과적으로 많은 로그들이 쌓이게 되지 않을까요?