繁体   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