And*_*eas 4 java spring reactive-programming spring-data-mongodb
我正在尝试学习如何使用MongoDB反应性存储库spring-boot 2.0.0.M2,但我担心我没有按预期做事.
这是我的方法之一,试图User通过他们的电子邮件找到.但如果没有,该方法应抛出异常.
@Override
public Mono<User> findByEmail(String email) {
User user = repository.findByEmail(email).block();
if(user == null) {
throw new NotFoundException("No user account was found with email: " + email);
}
return Mono.just(user);
}
Run Code Online (Sandbox Code Playgroud)
存储库扩展ReactiveCrudRepository<User, String>,但我担心通过使用.block()我阻止这种方法被反应.我是反应式编程的新手,我很难找到好的文档.有人可以指点我正确的方向吗?
mp9*_*1de 14
反应式编程需要端到端响应的流程,以获得来自反应式编程模型的实际好处..block()在流内调用强制执行同步并被视为反模式.
对于您的代码,只传播Mono您从中获取ReactiveCrudRepository并应用switchIfEmpty运算符以在Mono终止时发出错误信号而不发出值.nullReactive Streams规范(Project Reactor所基于的规范)中不允许使用这些值.如果结果不产生任何值,则Publisher不会发出值.
@Override
public Mono<User> findByEmail(String email) {
Mono<User> fallback = Mono.error(new NotFoundException("No user account was found with email: " + email));
return repository.findByEmail(email).switchIfEmpty(fallback);
}
Run Code Online (Sandbox Code Playgroud)
也可以看看:
| 归档时间: |
|
| 查看次数: |
5591 次 |
| 最近记录: |