简体   繁体   English

如何从将返回 mono 的可调用对象构建 mono?

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

I have this code that would call reactive Spring Redis Template to store some data I am stuck at the point of the switchIfEmpty where I want to create a new entry and store it and return the result.我有这段代码会调用 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")
                );
    }

I got to the point of x which gives me a Mono<String> but I need the fromCallable to return a String我到了x的地步,它给了我一个Mono<String>但我需要 fromCallable 来返回一个String

I am thinking if I just change switchIfEmpty to something else...我在想我是否只是将switchIfEmpty更改为其他内容......

As you can see at the docs Mono.fromCallable() accepts Callable<? extends T>正如您在文档中看到的那样 Mono.fromCallable() 接受Callable<? extends T> Callable<? extends T> , not Callable<? extends Mono<? extends T>> Callable<? extends T> ,而不是Callable<? extends Mono<? extends T>> Callable<? extends Mono<? extends T>> Callable<? extends Mono<? extends T>> , so it is not a surprise that you get Mono<Mono<...>> as result. Callable<? extends Mono<? extends T>> ,所以得到Mono<Mono<...>>结果并不奇怪。

You can try Mono.defer() instead of Mono.fromCallable().您可以尝试使用 Mono.defer()而不是 Mono.fromCallable()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM