redis 是否可以在browser上下文中调用subscribe?

bf1o4zei  于 7个月前  发布在  Redis
关注(0)|答案(1)|浏览(61)

我将加密密钥存储在Redis数据库中。我想实现一个回退机制来生成密钥,除非它们已经存在。我提出的解决方案让我感到困惑的是,我在一个Redis上下文中调用subscribe。我的IDE指出了这个问题。那么问题是如何实现这个回退?

public Mono<String> getEncryptionKey(String entity) {
    return reactiveRedisOperations.opsForValue()
            .get("private")
            .switchIfEmpty(
                    Mono.create(stringMonoSink -> {
                        try {
                            var privateKeyEncoded = ...
                            var publicKeyEncoded = ...

                            reactiveRedisOperations.opsForValue()
                                    .multiSet(Map.of(
                                            "private", privateKeyEncoded,
                                            "public", publicKeyEncoded
                                    ))
                                    .subscribe(success -> {
                                        stringMonoSink.success(privateKeyEncoded);
                                    });
                        } catch (Throwable e) {
                            stringMonoSink.error(e);
                        }
                    })
            );
}

字符串

dvtswwa3

dvtswwa31#

您可以使用Mono.defer(Supplier<? extends Mono<? extends T>> supplier)。它需要Mono的供应商,只有在Mono订阅时才会调用。在您的情况下,这意味着只有在switchIfEmpty的情况下才会调用密钥生成:

return reactiveRedisOperations.opsForValue()
            .get("private")
            .switchIfEmpty(Mono.defer(() -> {
                        var privateKeyEncoded = "...";
                        var publicKeyEncoded = "...";
                        return reactiveRedisOperations.opsForValue()
                                .multiSet(Map.of(
                                        "private", privateKeyEncoded,
                                        "public", publicKeyEncoded
                                ))
                                .map(b -> {
                                    if (b) return privateKeyEncoded;
                                    else throw new RuntimeException();
                                });
                    })
            );

字符串

相关问题