【发布时间】:2018-12-07 04:30:11
【问题描述】:
我想从 Flux/Mono 中获取对象/对象。 我用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
我会这样做:
Mono<UserEntity> byEmail = userRepository.findByEmail(userDto.getEmail());
UserEntity block = byEmail.block();
我有错误:
java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-3
为什么?有什么不同的方法来获取对象/对象?
在反应式编程中如何做一些事情: 在 RequestBody 中有 UserDto。
如果没有创建用户,请检查数据库中是否存在电子邮件。
@simon-baslé 的答复更新
return userRepository.findByEmail(userDto.getEmail())
//rethrow DB errors as BadRequestException, except user exists
.onErrorResume(t -> Mono.error(new BadRequestException()))
//throwing in map is converted to onError signal
.map(ifItGoesThereItExist-> { throw new UserByEmailExistException(); })
//switchIfEmpty to replace an empty source with a different Mono
.switchIfEmpty(createUser(userDto))
//at this point, map can only receive an onNext from the createUser
.map(u -> new ResponseEntity(u, HttpStatus.CREATED))
;
【问题讨论】:
-
所以,我无法获取对象,因为我无法阻止?那么如何检查用户是否存在于数据库中并返回异常用户存在呢?
-
如果您使用响应式编程,您应该订阅 Mono Publisher。
-
@GauravSrivastav 在这种情况下不是,Spring 框架会进行订阅
标签: java mongodb spring-boot project-reactor