Created
November 29, 2017 08:03
-
-
Save Ingwersaft/17189d26dbebb3fa70beafabd547d925 to your computer and use it in GitHub Desktop.
Kotlin: small resilience4j example using higher order functions
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
fun main(args: Array<String>) { | |
println("start") | |
val result = tryy { | |
circuitBreak { | |
rateLimit { | |
timeLimit { | |
"result string" | |
} | |
} | |
} | |
} | |
println("result='${result.getOrElse("failure")}'") | |
val timeOut = tryy { | |
circuitBreak { | |
rateLimit { | |
timeLimit { | |
Thread.sleep(5000L) | |
"result string" | |
} | |
} | |
} | |
} | |
println("result='${timeOut.getOrElse("failure")}'") | |
} | |
val defaultTimeLimiter = TimeLimiter.of(Duration.ofSeconds(1)) | |
fun <T> timeLimit(timeLimiter: TimeLimiter = defaultTimeLimiter, function: () -> T): T { | |
val future: Future<T> = CompletableFuture.supplyAsync(function) | |
val decorated = TimeLimiter.decorateFutureSupplier<T, Future<T>>(timeLimiter, Supplier { future }) | |
return decorated.call() | |
} | |
val defaultRateLimiter = RateLimiter.ofDefaults("default") | |
fun <T> rateLimit(rateLimiter: RateLimiter = defaultRateLimiter, function: () -> T): T { | |
return RateLimiter.decorateSupplier(rateLimiter, function).get() | |
} | |
fun <T> tryy(function: () -> T): Try<T> { | |
return Try.ofCallable(function) | |
} | |
val defaultCircuitBreaker = CircuitBreaker.ofDefaults("default") | |
fun <T> circuitBreak(circuitBreaker: CircuitBreaker = defaultCircuitBreaker, function: () -> T): T { | |
var decoratedSupplier = CircuitBreaker.decorateSupplier(circuitBreaker, function) | |
return decoratedSupplier.get() | |
} | |
//gradle: | |
//ext {set("resilience4jVersion", "0.10.1")} | |
//compile(group = "io.github.resilience4j", name = "resilience4j-circuitbreaker", version = ext["resilience4jVersion"] as String) | |
//compile(group = "io.github.resilience4j", name = "resilience4j-ratelimiter", version = ext["resilience4jVersion"] as String) | |
//compile(group = "io.github.resilience4j", name = "resilience4j-retry", version = ext["resilience4jVersion"] as String) | |
//compile(group = "io.github.resilience4j", name = "resilience4j-timelimiter", version = ext["resilience4jVersion"] as String) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment