我正在使用 aRouterFunction
在我的 Spring Boot 應用程式中定義端點。我的服務回傳一個Mono<Object>
,我想在呼叫端點時回傳這個結果。我還需要進行身份驗證,因此我傳遞了一個UserPrinciple
物件。
路由器
@Bean
RouterFunction<ServerResponse> router() {
return route()
.GET("/api/endpoint-name", this::getExample)
.build();
}
private Mono<ServerResponse> getExample(ServerRequest request) {
return ServerResponse.ok().body(fromPublisher(getUserPrincipal().map(service::getSomething), Object.class)).log();
}
private Mono<UserPrincipal> getUserPrincipal() {
return ReactiveSecurityContextHolder.getContext()
.map(ctx -> ctx.getAuthentication())
.map(auth -> auth.getPrincipal())
.map(UserPrincipal.class::cast);
}
服務
public Mono<Object> getSomething(UserPrincipal userPrincipal) {
WebClient webClient = getWebClient(userPrincipal.getJwt());
return webClient.get()
.uri(uriBuilder -> uriBuilder.path("another/server/endpoint").build())
.retrieve()
.bodyToMono(Object.class);
}
端點回傳這個:
{
"scanAvailable": true
}
這表明我將傳遞Mono
到回應的正文中,而不是傳遞結果。但是,我使用fromPublisher
了我認為可以解決此問題的方法。
我找不到任何服務回傳 aMono
并且路由正確回傳Mono
.
如何正確傳遞 aMono/Flux
作為回應的正文?
uj5u.com熱心網友回復:
我不打算解釋和之間的區別map
,flatMap
因為我已經在這里寫了一個非常全面的解釋:
你有測驗來顯示 reactor map() 和 flatMap() 之間的差異嗎?
上面代碼中的問題是Object
. 并將引數輸入Object
到某些函式中。第一個功能非常簡單
Mono<UserPrincipal> = getUserPrincipal();
而第二個變得有點毛茸茸:
Mono<Mono<Object> value = getUserPrincipal().map(service::getSomething);
那么為什么我們得到一個嵌套的 Mono?,那么 get something 回傳 aMono<Object>
并且Map
根據 api 的回傳是我們從Mono<R>
哪里回傳的。R
getSomething
然后,我們將其粘貼到fromPublisher
將解開第一個Mono
最終嘗試序列化Mono<Object>
結果的奇怪回應中。
{
"scanAvailable": true
}
這里的答案是更加關注型別系統。該body
函式采用Publisher
(Mono 或 Flux),因此您不需要該fromPublisher
函式。
并且也更改map
為,flatMap
因為 a 內部的回傳型別flatMap
是 a publisher
。
ServerResponse.ok()
.body(getUserPrincipal()
.flatMap(service::getSomething), Object.class));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/468249.html
標籤:爪哇 弹簧靴 spring-webflux