簡體   English   中英

如何從將返回 mono 的可調用對象構建 mono?

[英]How do I build a mono from a callable that would return a mono?

我有這段代碼會調用 reactive Spring Redis 模板來存儲一些數據我被困在 switchIfEmpty 的位置,我想創建一個新條目並存儲它並返回結果。

    public Mono<SecretKey> secretKey(String jti, int expiresInSeconds) {

        final var urlDecoder = Base64.getUrlDecoder();
        var ops = redisTemplate.opsForValue();
        return ops.getAndExpire(simpleAuthServiceProperties + ":::symmetricKeys:::"+ jti, Duration.ofSeconds(expiresInSeconds))
                .switchIfEmpty(Mono.fromCallable(() -> {
                    final var secretKey = keyGenerator.generateKey();
                    final var encoded = secretKey.getEncoded();
                    final var e = Base64.getUrlEncoder().encodeToString(encoded);
                    var x = ops.setIfAbsent(simpleAuthServiceProperties + ":::symmetricKeys:::"+ jti, e, Duration.ofSeconds(expiresInSeconds))
                            .flatMap(result -> {
                                if (result) {
                                    return Mono.just(e);
                                } else {
                                    return Mono.error(IllegalStateException::new);
                                }
                            });
                    return x;
                }))
                .map(urlDecoder::decode)
                .map(bytes->
                    new SecretKeySpec(bytes, "AES")
                );
    }

我到了x的地步,它給了我一個Mono<String>但我需要 fromCallable 來返回一個String

我在想我是否只是將switchIfEmpty更改為其他內容......

正如您在文檔中看到的那樣 Mono.fromCallable() 接受Callable<? extends T> Callable<? extends T> ,而不是Callable<? extends Mono<? extends T>> Callable<? extends Mono<? extends T>> Callable<? extends Mono<? extends T>> ,所以得到Mono<Mono<...>>結果並不奇怪。

您可以嘗試使用 Mono.defer()而不是 Mono.fromCallable()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM