Created
August 11, 2020 22:37
-
-
Save MWhyte/928871220ad8dc797897ae08a75ff9d6 to your computer and use it in GitHub Desktop.
A simple resilience4j retry example written in kotlin
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
import io.github.resilience4j.retry.Retry | |
import io.github.resilience4j.retry.RetryConfig | |
import io.github.resilience4j.retry.RetryRegistry | |
import java.time.Duration | |
import java.util.function.Supplier | |
var x = 0 | |
fun main() { | |
getWithRetry() | |
} | |
fun getWithRetry(): String { | |
val config = createRetryConfig() | |
val registry = RetryRegistry.of(config) | |
val retry: Retry = registry.retry("my-first-retry") | |
val decorateFunction: Supplier<String> = Retry.decorateSupplier(retry) { | |
get() | |
} | |
return decorateFunction.get() | |
} | |
private fun createRetryConfig(): RetryConfig { | |
return RetryConfig.custom<Any>() | |
.maxAttempts(3) | |
.waitDuration(Duration.ofMillis(100)) | |
.retryExceptions(NullPointerException::class.java) | |
.retryOnResult { response -> checkResult(response as String) } | |
.build() | |
} | |
private fun checkResult(response: String): Boolean { | |
return response == "error response" | |
} | |
private fun get(): String { | |
x++ | |
println("called with x=${x}") | |
return when (x) { | |
1 -> throw java.lang.NullPointerException("really!!!") | |
2 -> "error response" | |
else -> { // Note the block | |
return "winner" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment