1 回答

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
文檔確實(shí)需要更新,我認(rèn)為在#5055 的websockets 重構(gòu)中遺漏了一些位。
要獲得異步處理,您應(yīng)該使用acceptOrResult
以 aCompletionStage
作為返回類型而不是流的方法。然后可以使用函數(shù)式編程助手 ( ) 返回 aResult
或 Akka?。事實(shí)上,下面是該方法的實(shí)現(xiàn)方式:Flow
F.Either
accept
public?WebSocket?accept(Function<Http.RequestHeader,?Flow<In,?Out,??>>?f)?{? ??return?acceptOrResult( ???????request?->?CompletableFuture.completedFuture(F.Either.Right(f.apply(request)))); }
如您所見,它所做的只是調(diào)用帶有completedFuture
.
為了完全使其異步并達(dá)到我認(rèn)為你想要實(shí)現(xiàn)的目標(biāo),你會(huì)做這樣的事情:
public WebSocket ws() {
? ? return WebSocket.Json.acceptOrResult(request -> {
? ? ? ? if (sameOriginCheck(request)) {
? ? ? ? ? ? final CompletionStage<Flow<JsonNode, JsonNode, NotUsed>> future = wsFutureFlow(request);
? ? ? ? ? ? final CompletionStage<Either<Result, Flow<JsonNode, JsonNode, ?>>> stage = future.thenApply(Either::Right);
? ? ? ? ? ? return stage.exceptionally(this::logException);
? ? ? ? } else {
? ? ? ? ? ? return forbiddenResult();
? ? ? ? }
? ? });
}
@SuppressWarnings("unchecked")
private CompletionStage<Flow<JsonNode, JsonNode, NotUsed>> wsFutureFlow(Http.RequestHeader request) {
? ? long id = request.asScala().id();
? ? UserParentActor.Create create = new UserParentActor.Create(Long.toString(id));
? ? return ask(userParentActor, create, t).thenApply((Object flow) -> {
? ? ? ? final Flow<JsonNode, JsonNode, NotUsed> f = (Flow<JsonNode, JsonNode, NotUsed>) flow;
? ? ? ? return f.named("websocket");
? ? });
}
private CompletionStage<Either<Result, Flow<JsonNode, JsonNode, ?>>> forbiddenResult() {
? ? final Result forbidden = Results.forbidden("forbidden");
? ? final Either<Result, Flow<JsonNode, JsonNode, ?>> left = Either.Left(forbidden);
? ? return CompletableFuture.completedFuture(left);
}
private Either<Result, Flow<JsonNode, JsonNode, ?>> logException(Throwable throwable) {
? ? logger.error("Cannot create websocket", throwable);
? ? Result result = Results.internalServerError("error");
? ? return Either.Left(result);
}
(這取自play-java-websocket-example,這可能很有趣)
如您所見,它首先經(jīng)過幾個(gè)階段,然后返回 websocket 連接或 HTTP 狀態(tài)。
添加回答
舉報(bào)