为什么 Webflux 'then' 运算符不执行?

问题描述 投票:0回答:0
    public Mono<Integer> saveAccount(Mono<AccountSaveRequest> requestMono) {
        var reqMono = requestMono.map(AccountSaveRequest::convertEntity);
        return reqMono.flatMap(req -> this.accountRepository.findByAccount(req.account()).doOnNext(model -> {
            if (req.id() == null || !model.id().equals(req.id())) {
                throw new BusinessException("account exists");
            }})
        ).then(reqMono).flatMap(req -> StringUtils.hasText(req.mobile()) ? this.accountRepository.findByMobile(req.mobile()).doOnNext(model -> {
            if (req.id() == null || !model.id().equals(req.id())) {
                throw new BusinessException("mobile exists");
            }
        }) : Mono.empty()).then(Mono.defer(() -> reqMono.flatMap(this.accountRepository::save))).map(AccountEntity::id);
    }

看代码,简单易懂,这个方法是用来保存一个用户到数据库的。

首先从请求中接收一个 AccountSaveRequest 模型并映射到 AccountEntity,然后检查是否 “帐户”字段已存在于数据库中。

如果不存在,我使用'then(reqMono)'运算符切换到另一个Mono,下面的Mono用于检查字段'mobile'是否已经存在于数据库中,如果mobile不为空。

如果 mobile 仍然不存在,我最后将帐户保存到数据库并将 id 返回给消费者。

如果一切正常,该方法将返回一个id。但是'then(reqMono)'之后的代码不执行。

我用另一种方式试过了,看代码

    public Mono<Integer> saveAccount(Mono<AccountSaveRequest> requestMono) {
        return requestMono.map(AccountSaveRequest::convertEntity).flatMap(req -> this.accountRepository.findByAccount(req.account()).doOnNext(model -> {
            if (req.id() == null || !model.id().equals(req.id())) {
                throw new BusinessException("account exists");
            }}).switchIfEmpty(Mono.defer(() -> StringUtils.hasText(req.mobile()) ? this.accountRepository.findByMobile(req.mobile()).doOnNext(model -> {
                if (req.id() == null || !model.id().equals(req.id())) {
                    throw new BusinessException("mobile exists");
                }
            }) : Mono.empty())).then(Mono.defer(() -> this.accountRepository.save(req))).map(AccountEntity::id)
        );
    }

我将 'then(reqMono)' 之后的代码包装到第一个 flatMap 调用中,它工作正常

能找到问题吗? THKS

spring-webflux project-reactor
© www.soinside.com 2019 - 2024. All rights reserved.