【问题标题】:Spring webclient: Multiple requests simultaneouslySpring webclient:同时多个请求
【发布时间】:2020-05-04 15:49:16
【问题描述】:

是否可以在 Web 客户端上将多个请求链接在一起?例如,我希望能够在进行交易时更新买卖双方的余额。现在它只是更新买家余额:


    public Mono<Void> isAccountBalanceGreater(Account acc, Product prd) {


       double newBuyerBalance  =acc.getBalance() - prd.getPrice();

       Mono<Account> seller =  webClientBuilder.build().get().uri("http://account-service/user/accounts/{userId}/", prd.getProductId())
    .retrieve().bodyToMono(Account.class)
    .map(a-> new Account(a.getAccountId(),a.getOwner(),a.getPin(),a.getBalance()+prd.getPrice(),a.getUserId()));

    Account newOwnerAcc = new Account(acc.getAccountId(),acc.getOwner(),acc.getPin(),newBuyerBalance,acc.getUserId());


return webClientBuilder.build().put()
.uri("http://account-service/account/update/{accountId}",acc.getAccountId())
.body(Mono.just(newOwnerAcc),Account.class)
.retrieve().bodyToMono(Void.class);





        }

有没有办法可以同时调用两个 put 方法,以便更新两个余额?

更新:此方法适用于将单声道值调用为 uri 变量。

    return acc.flatMap(a->{


               UriComponents urlc = UriComponentsBuilder.fromUriString("http://account-service/account/update/{accountId}")
                       .encode().build();

               URI uri = urlc.expand(a.getAccountId()).toUri();

                return webClientBuilder.build().put()
                         .uri(uri)
                             .body(acc,Account.class).retrieve().bodyToMono(Void.class);
            });


【问题讨论】:

    标签: spring webclient spring-webflux


    【解决方案1】:

    为了简化,我将提取 webclient 调用到单独的方法:

    Mono<Void> webClientCall(Account acc) {
     return webClientBuilder.build().put()
        .uri("http://account-service/account/update/{accountId}",acc.getAccountId())
        .body(Mono.just(newOwnerAcc),Account.class)
        .retrieve().bodyToMono(Void.class);
    }
    

    假设你有帐户,你可以使用zipthen 运算符:

    Account acc1;
    Account acc2; 
    
    return webClientCall(acc1).zipWith(webClientCall(acc2))
             .then();
    
    

    【讨论】:

    • 甚至return webClientCall(acc1).then(webClientCall(acc2));
    • 如果我的第二个帐户是单声道,因为我是通过 webclient 检索它,该怎么办?
    • return webClientCall(acc1).map(acc2 -&gt; { return webClientCall(acc2); }) 也许?
    • 我对一种可能的方法进行了更新,但它还不能正常工作。您认为这是正确的方法吗?
    • 谢谢,这和其他一些改变让它工作了,我在上面更新了
    猜你喜欢
    • 2021-06-23
    • 2019-09-19
    • 2020-01-30
    • 2020-07-11
    • 2018-02-23
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多