Repository repo
Repository otherRepo
foreach entity : repo.FindAll() {
entityFind = otherRepo.FindById(entity.Prop)
if (entityFind != null) {
return entityFind
}
}我如何使用spring reactive来做到这一点呢?
我可以使用blockFirst()在otherRepo中进行搜索,但它会中断反应链
我也尝试过使用句柄()来控制流程,但当我找到一个项目时,我无法中断流程
有什么想法吗?谢谢
发布于 2020-03-10 00:45:43
如果您有类似这样的repos,对于repo1的每条记录,如果您需要从repo2中查找一条记录,您可能可以使用spring data JPQL连接表&使用您的自定义方法,因为您当前的方法可能会对性能产生影响。
因为你似乎只对第一张记录感兴趣,只是为了给你一个想法,我们可以实现这样的事情。
return Flux.fromIterable(repo.findAll()) //assuming it returns a list
.map(entity -> otherRepo.findById(entity.property)) // for each entity we query the other repo
.filter(Objects::nonNull) // replace it with Optional::isPresent if it is optional
.next(); //converts the flux to mono with the first record发布于 2020-03-11 21:16:49
来自vins的答案是假设非反应式存储库,所以这里是完全反应式的:
return repo.findAll() //assuming reactive repository, which returns Flux<Entity>
.flatMap(entity -> otherRepo.findById(entity.property)) //findById returns an empty Mono if id not found, which basically gets ignored by flatMap
.next(); //first record is turned into a Mono, and the Flux is cancelled注意,正如您所说的,这可能会导致向Cassandra发出不必要的请求(然后被next()取消)。这是由于flatMap允许多个并发请求(默认情况下为256个)。您可以减少flatMap的parallelism (通过提供第二个参数int),也可以使用concatMap串行执行findById查询。
https://stackoverflow.com/questions/60604247
复制相似问题