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.
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
I am thinking if I just change switchIfEmpty
to something else...
As you can see at the docs Mono.fromCallable() accepts Callable<? extends T>
Callable<? extends T>
, not 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.
You can try Mono.defer() instead of Mono.fromCallable().
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.