【发布时间】:2020-07-05 13:53:08
【问题描述】:
我正在使用 webflux 框架进行 Spring Boot,我试图实现的行为是在数据库中创建一个新客户,如果它不存在(如果存在则抛出异常) 并维护另一个国家代码数据库(如果新客户来自新国家,则添加到数据库中,如果国家已保存,则使用旧信息)
这是服务中的功能:
public Mono<Customer> createNewCustomer(Customer customer) {
if(!customer.isValid()) {
return Mono.error(new BadRequestException("Bad email or birthdate format"));
}
Mono<Customer> customerFromDB = customerDB.findByEmail(customer.getEmail());
Mono<Country> countryFromDB = countryDB.findByCountryCode(customer.getCountryCode());
Mono<Customer> c = customerFromDB.zipWith(countryFromDB).doOnSuccess(new Consumer<Tuple2<Customer, Country>>() {
@Override
public void accept(Tuple2<Customer, Country> t) {
System.err.println("tuple " + t);
if(t == null) {
countryDB.save(new Country(customer.getCountryCode(), customer.getCountryName())).subscribe();
customerDB.save(customer).subscribe();
return;
}
Customer cus = t.getT1();
Country country = t.getT2();
if(cus != null) {
throw new CustomerAlreadyExistsException();
}
if(country == null) {
countryDB.save(new Country(customer.getCountryCode(), customer.getCountryName())).subscribe();
}
else {
customer.setCountryName(country.getCountryName());
}
customerDB.save(customer).subscribe();
}
}).thenReturn(customer);
return c;
}
我的问题是,如果没有找到国家或客户,则元组返回 null,而我需要单独了解它们是否存在,以便我可以正确保存到数据库中。
country == null 绝不是真的
我也尝试使用customerFromDB.block() 来获取实际值,但我收到一个不支持的错误,所以我猜不是这样
是否有两种查询来获取它们的值?
【问题讨论】:
标签: spring mongodb mono spring-webflux reactive