0
votes

Is it possible to chain multiple requests together on a webclient? For example, I want to be able to update the balances of both buyer and seller when a transaction is made. Right now It just updates the buyer balance:


    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);





        }

Is there a way I can call two put methods together so both balances will be updated?

Update: this method works for calling a mono value as a uri variable.

    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);
            });


1

1 Answers

1
votes

To simplify I will extract webclient call to separate method:

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);
}

Assuming that you have to accounts you can use zip and then operators:

Account acc1;
Account acc2; 

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