反应式编程如何实现依赖结果
Reactive programming how to implement dependent result
我正在尝试通过 spring 启动来使用反应模式 REST 服务。我已经设置了代码,它正在努力将项目保存在 Cassandara 数据库中。现在我有以下要求以反应方式编写:
如果在数据库中找不到项目,请保存该项目。如果 Item 存在则抛出异常。
我一直在尝试弄清楚如何以反应方式执行此类逻辑。由于我是这个领域的初学者,所以很难理解这个概念。以下是我的做法:
@Override
public Mono<String> createItem(ItemCreateParam itemCreateParam) {
//This check if item exits in database.
Mono<Boolean> byName = reactiveItemRepository.existsById(itemCreateParam.getName());
//This save the item and return the id (i.e name)
return Mono.just(itemCreateParam)
.flatMap(item -> convert(item))
.log()
.flatMap(t -> reactiveTemplateRepository.save(t))
.map(t-> t.getName());
}
如何以反应方式将这两者结合起来?
只需查看 existsWithId()
的结果。这就是我要实现的方式:
@Override
public Mono<String> createItem(ItemCreateParam itemCreateParam) {
return reactiveItemRepository.existsById(itemCreateParam.getName())
.doOnNext(exists -> {
if (exists) {
throw new AppException(ErrorCode.ITEM_EXISTS);
}
})
.flatMap(exists -> convert(item))
.flatMap(converted -> reactiveTemplateRepository.save(converted))
.map(saved -> saved.getName());
}
请注意 AppException
类型可以是任何其他类型,但它应该扩展 RuntimeException
.
我正在尝试通过 spring 启动来使用反应模式 REST 服务。我已经设置了代码,它正在努力将项目保存在 Cassandara 数据库中。现在我有以下要求以反应方式编写:
如果在数据库中找不到项目,请保存该项目。如果 Item 存在则抛出异常。
我一直在尝试弄清楚如何以反应方式执行此类逻辑。由于我是这个领域的初学者,所以很难理解这个概念。以下是我的做法:
@Override
public Mono<String> createItem(ItemCreateParam itemCreateParam) {
//This check if item exits in database.
Mono<Boolean> byName = reactiveItemRepository.existsById(itemCreateParam.getName());
//This save the item and return the id (i.e name)
return Mono.just(itemCreateParam)
.flatMap(item -> convert(item))
.log()
.flatMap(t -> reactiveTemplateRepository.save(t))
.map(t-> t.getName());
}
如何以反应方式将这两者结合起来?
只需查看 existsWithId()
的结果。这就是我要实现的方式:
@Override
public Mono<String> createItem(ItemCreateParam itemCreateParam) {
return reactiveItemRepository.existsById(itemCreateParam.getName())
.doOnNext(exists -> {
if (exists) {
throw new AppException(ErrorCode.ITEM_EXISTS);
}
})
.flatMap(exists -> convert(item))
.flatMap(converted -> reactiveTemplateRepository.save(converted))
.map(saved -> saved.getName());
}
请注意 AppException
类型可以是任何其他类型,但它应该扩展 RuntimeException
.