简体   繁体   中英

How to Send multiple POST request through Java Spring Webflux

I have a json file of an array with objects. I would like to iterate through each object and send a post request with the body inside. My issue or question is trying to iterate through the @RequestBody for each object in the array and call the createObj method.

I pasting the json into Postman to test it I already have a createObject like so but it works for a Mono not multiple

I tried iterating it like so

@PostMapping(path = "multicreate", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Flux<Hospital> createMultipleHospital(@RequestBody Flux<Hospital> hospital) {
   hospital.collectList().flatMap(x -> {
        return hospitalService.createHospital((Mono<Hospital>) x);
    });
       return null;
}
// Should loop and send 2 POST request.
[
  {
      "name": "Miami Cancer Institute",
      "address": "8900 North Kendall Drive",
      "phone": "786-596-2000",
      "zipcode": "33176",
      "city": "Miami",
      "state": "FL"
   },
   {
      "name": "Mercy Hospital",
      "address": "3663 S Miami Ave",
      "phone": "305-854-4400",
      "zipcode": "33133",
      "city": "Miami",
      "state": "FL"
   }
]

Controller

@PostMapping(path = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Mono<Hospital> createHospital(@RequestBody Mono<Hospital> hospital) {
    System.out.println(hospital);
    return hospitalService.createHospital(hospital);
}

Service/Repository

@Override
public Mono<Hospital> createHospital(Mono<Hospital> hospitalMono) {
  return hospitalMono.flatMap(hosp -> {
     try {
        return reactiveMongoOperations.save(
           hosp.createLatCord(hosp));
          } catch (InterruptedException | ApiException | IOException e) {
              e.printStackTrace();
          }
            return Mono.just(hosp);
        });
}

Solved it after i just switched method return type and parameter from MONO to FLUX and worked.

@Override
    public Flux<Hospital> createHospital(Flux<Hospital> hospitalMono) {
        return hospitalMono.flatMap(hosp -> {
            try {
                return reactiveMongoOperations.save(
                        hosp.createLatCord(hosp));
            } catch (InterruptedException | ApiException | IOException e) {
                e.printStackTrace();
            }
            return Mono.just(hosp);
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM