[英]Spring Webflux SSE server: how to send error to the client and close connection
我有一個 Spring WebFlux 應用程序服務器,它在連接時將 SSE 無限發送給最終用戶。 我想實現某種id
驗證,它依賴於從 3rd 方服務請求 id,返回Mono<Boolean>
。 如果上面的Mono
包含false
,我想關閉錯誤的連接。
問題是我無法從handleSse
方法返回Mono.error()
(因為它必須返回Flux<ServerSentEvent<UserUpdateResponse>>
)。
如何正確向用戶發送錯誤並在之后關閉連接?
這是我的代碼:
@GetMapping("/sse")
public Flux<ServerSentEvent<UserUpdateResponse>> handleSse(String id) {
return usersSink.asFlux()
.filter(update -> id.equals(update.getId()))
.map(this::wrapIntoSse);
}
private ServerSentEvent<UserUpdateResponse> wrapIntoSse(UserUpdate userUpdate) {
return ServerSentEvent.builder(new UserResponse(userUpdate.getUserCode()))
.event("user-update")
.build();
}
因此,在為此苦苦掙扎了一段時間后,我得出了這個解決方案:
@GetMapping("/sse")
public Flux<ServerSentEvent<UserUpdateResponse>> handleSse(@RequestParam(required = false) String id) {
if (StringUtils.isBlank(id)) {
throw new WebServiceRuntimeException(HttpStatus.BAD_REQUEST, "The \"id\" parameter is missing");
}
final Mono<Boolean> cached = cacheService.getgetUser(id);
return Flux.from(cached).flatMap(exists -> {
if (exists) {
return userUpdateSink.asFlux()
.filter(update -> id.equals(update.getgetUser()))
.map(this::wrapIntoSse);
}
return Flux.error(new WebServiceRuntimeException(HttpStatus.NOT_FOUND,
"The specified \"user\" does not exist: " + id + "."));
}
);
}
@GetMapping("/sse")
public Flux<ServerSentEvent> handleSse(@RequestParam(required = false) String id) {
if (StringUtils.isBlank(id)) {
throw new WebServiceRuntimeException(HttpStatus.BAD_REQUEST, "The "id" parameter is missing");
}
final Mono cached = cacheService.getgetUser(id);
return Flux.from(cached).flatMap(exists -> {
if (exists) {
return userUpdateSink.asFlux().filter(update -> id.equals(update.getgetUser())).map(this::wrapIntoSse);
}
return Flux.error(new WebServiceRuntimeException(HttpStatus.NOT_FOUND, "The specified "user" does not exist: " + id + "."));
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.