我一直在寻找问题作者所描述的相同问题的解决方案。最后,我想出了以下用于创建路由的 Java 代码:
ActorRef ref = system.actorOf(Props.create(RequestHandlerActor.class));
return get(() -> route(
pathSingleSlash(() ->
extractRequest(httpRequest -> {
Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS));
CompletionStage<HttpResponse> completionStage = PatternsCS.ask(ref, httpRequest, timeout)
.thenApplyAsync(HttpResponse.class::cast);
return completeWithFuture(completionStage);
})
))
);
并且RequestHandlerActor
是:
public class RequestHandlerActor extends UntypedActor {
@Override
public void onReceive(Object msg) {
if (msg instanceof HttpRequest) {
HttpResponse httpResponse = HttpResponse.create()
.withEntity(ContentTypes.TEXT_HTML_UTF8,
"<html><body>Hello world!</body></html>");
getSender().tell(httpResponse, getSelf());
} else {
unhandled(msg);
}
}
}