Created
August 19, 2017 09:27
-
-
Save ris58h/9a3322c7e2989015e3dc09370b42ff7b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 reactor.core.publisher.Mono; | |
import reactor.ipc.netty.http.client.HttpClient; | |
import reactor.ipc.netty.http.client.HttpClientResponse; | |
import reactor.ipc.netty.http.server.HttpServer; | |
import reactor.ipc.netty.http.server.HttpServerRoutes; | |
import java.nio.charset.Charset; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
public class ReactorFibonacci { | |
private static final String HOST = "localhost"; | |
private static final int PORT = 8888; | |
public static void main(String[] args) { | |
Function<Long, Mono<Long>> fibonacci = fibonacci(httpClient()); | |
Consumer<HttpServerRoutes> routesBuilder = routesBuilder(fibonacci); | |
HttpServer httpServer = HttpServer.create(HOST, PORT); | |
httpServer.startRouterAndAwait(routesBuilder, null); | |
} | |
private static Consumer<HttpServerRoutes> routesBuilder(Function<Long, Mono<Long>> fibonacci) { | |
return routes -> routes.get("/{n}", (request, response) -> { | |
Long n = Long.valueOf(request.param("n")); | |
if (n <= 2) { | |
return response.sendString(Mono.just("1")); | |
} else { | |
Mono<Long> n_1 = fibonacci.apply(n - 1); | |
Mono<Long> n_2 = fibonacci.apply(n - 2); | |
Mono<Long> sum = n_1.and(n_2, Long::sum); | |
return response.sendString(sum.map(String::valueOf)); | |
} | |
}); | |
} | |
static HttpClient httpClient() { | |
return HttpClient.create(HOST, PORT); | |
} | |
static Function<Long, Mono<Long>> fibonacci(HttpClient httpClient) { | |
return n -> httpClient.get("/" + n) | |
.flatMap((Function<HttpClientResponse, Mono<String>>) response -> response | |
.receive() | |
.aggregate() | |
.asString(Charset.forName("UTF-8"))) | |
.map(Long::valueOf); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment