Project Reactor 条件执行
Project Reactor conditional execution
我有一个对象要保存(到 MongoDB),但在此之前我需要检查某些条件是否为真。
对象包含其他对象的 ID。看起来像
"object": {
"id": "123",
"subobject1": { "id": "1" },
"subobject2": { "id": "2" }
}
子对象只包含id,其他信息位于其他集合中,所以我必须检查信息是否存在。
在块样式中我可以做类似的事情
if (!languageRepository.exists(Example.of(wordSet.getNativeLanguage())).block()) {
throw new RuntimeException("Native language doesn't exist");
}
if (!languageRepository.exists(Example.of(wordSet.getTargetLanguage())).block()) {
throw new RuntimeException("Target language doesn't exist");
}
只有这样我才能保存我的对象
return wordSetRepository.save(wordSet);
如何在不阻塞的情况下以 "reactive" 样式进行操作?
如果你想为本地语言和目标语言错误情况传播不同的错误,你需要在 flatMap
:
中执行异步过滤
objectFlux.flatMap(o ->
Mono.just(o)
.filterWhen(languageRepository.exists(...)) //native
.switchIfEmpty(Mono.error(new RuntimeException("Native language doesn't exist"))
.filterWhen(languageRepository.exists(...)) //target
.switchIfEmpty(Mono.error(new RuntimeException("Target language doesn't exist"))
)
.flatMap(wordSetRepository::save);
flatMap
内部的异步过滤确保如果测试未通过,则内部序列为空。这反过来又允许我们检测案例并传播足够的错误。如果两个测试都通过,则原始 o
在主序列中传播。
第二个flatMap
从那里获取它,只接收通过两个过滤器的元素并将它们保存在数据库中。
请注意,第一个未通过过滤器的元素将中断整个序列(但在抛出异常后的阻塞代码中也是如此)。
我有一个对象要保存(到 MongoDB),但在此之前我需要检查某些条件是否为真。
对象包含其他对象的 ID。看起来像
"object": {
"id": "123",
"subobject1": { "id": "1" },
"subobject2": { "id": "2" }
}
子对象只包含id,其他信息位于其他集合中,所以我必须检查信息是否存在。
在块样式中我可以做类似的事情
if (!languageRepository.exists(Example.of(wordSet.getNativeLanguage())).block()) {
throw new RuntimeException("Native language doesn't exist");
}
if (!languageRepository.exists(Example.of(wordSet.getTargetLanguage())).block()) {
throw new RuntimeException("Target language doesn't exist");
}
只有这样我才能保存我的对象
return wordSetRepository.save(wordSet);
如何在不阻塞的情况下以 "reactive" 样式进行操作?
如果你想为本地语言和目标语言错误情况传播不同的错误,你需要在 flatMap
:
objectFlux.flatMap(o ->
Mono.just(o)
.filterWhen(languageRepository.exists(...)) //native
.switchIfEmpty(Mono.error(new RuntimeException("Native language doesn't exist"))
.filterWhen(languageRepository.exists(...)) //target
.switchIfEmpty(Mono.error(new RuntimeException("Target language doesn't exist"))
)
.flatMap(wordSetRepository::save);
flatMap
内部的异步过滤确保如果测试未通过,则内部序列为空。这反过来又允许我们检测案例并传播足够的错误。如果两个测试都通过,则原始 o
在主序列中传播。
第二个flatMap
从那里获取它,只接收通过两个过滤器的元素并将它们保存在数据库中。
请注意,第一个未通过过滤器的元素将中断整个序列(但在抛出异常后的阻塞代码中也是如此)。