31 Temmuz 2021 Cumartesi

SpringWebFlux WebClient Mono Dönüşümü

Giriş
WebClient cevabını Mono'ya dönüştürmek için yöntemler şöyle

1. bodyToMono
Örnek
Şöyle yaparız
WebClient webClient = WebClient.create();
Mono<String> responseOne = webClient.get()
    .uri("http://example.com/endpointOne")
    .retrieve()
    .bodyToMono(String.class);

Mono<String> responseTwo = webClient.get()
    .uri("http://example.com/endpointTwo")
    .retrieve()
    .bodyToMono(String.class);

// Use Mono.zip to execute requests concurrently
Mono.zip(responseOne, responseTwo).subscribe(results -> {
    System.out.println("Result 1: " + results.getT1());
    System.out.println("Result 2: " + results.getT2());
});

2. exchangeToMono Yöntemi
Örnek
Şöyle yaparız
WebClient webClient = WebClient.create();
Mono<String> getHttpNonBlocking(String url) {
    return webClient
            .get()
            .uri(url)
            .exchangeToMono(cr -> cr.bodyToMono(String.class));
}
3. exchange + flatmap Yöntemi
Örnek
Elimizde şöyle bir kod olsun. Bu kod hem Mono hem de Flux dönebiliyor. Hem get() hem de put() işlemi için exchange() çağrısı yapıyor. Kod bir  spring bean. İskeleti şöyle
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

@Component
public class WebClientHelper {

  private WebClient webClient;

  public WebClientHelper() {
    webClient = WebClient.create();
  }
}
Get ve Post için Mono dönen metodlar şöyle
public <T> Mono<T> performGetToMono(URI uri, MultiValueMap<String, String> params,
Class<? extends T> clazzResponse){
    return webClient.get()
        .uri(uriBuilder -> uriBuilder.scheme(uri.getScheme()).host(uri.getHost())
            .port(uri.getPort()).path(uri.getPath()).queryParams(params).build()
        )
        .exchange()
        .flatMap(clientResponse -> clientResponse.bodyToMono(clazzResponse));
}
public <T> Mono<T> performPostToMono(URI uri, Object requestBody,
Class<? extends T> clazzResponse){
    return webClient.post()
        .uri(uriBuilder -> uriBuilder.scheme(uri.getScheme()).host(uri.getHost())
            .port(uri.getPort()).path(uri.getPath()).build()
        )
        .body(BodyInserters.fromValue(requestBody))
        .exchange()
        .flatMap(clientResponse -> clientResponse.bodyToMono(clazzResponse));
}
Put ve Delete için Mono dönen metodlar şöyle
public <T> Mono<T> performPutToMono(URI uri, Object requestBody,
Class<? extends T> clazzResponse){
    return webClient.put()
        .uri(uriBuilder -> uriBuilder.scheme(uri.getScheme()).host(uri.getHost())
            .port(uri.getPort()).path(uri.getPath()).build()
        )
        .body(BodyInserters.fromValue(requestBody))
        .exchange()
        .flatMap(clientResponse -> clientResponse.bodyToMono(clazzResponse));
}
public <T> Mono<T> performDeleteToMono(URI uri, MultiValueMap<String, String> params,
Class<? extends T> clazzResponse){
    return webClient.delete()
        .uri(uriBuilder -> uriBuilder.scheme(uri.getScheme()).host(uri.getHost())
            .port(uri.getPort()).path(uri.getPath()).queryParams(params).build()
        )
        .exchange()
        .flatMap(clientResponse -> clientResponse.bodyToMono(clazzResponse));
}
Bu kodu kullanmak için şöyle yaparız
@RestController
@RequestMapping("/employeeClient")
public class EmployeeClientController {

  @Value("${employee.server.host}")
  private String employeeHost;

  @Autowired
  private WebClientHelper webClientHelper;

  @GetMapping("/{employeeId}")
  public Mono<EmployeeModel> getEmployeeById(@PathVariable("employeeId")
String employeeId){
    String url = ApiPaths.getEmployeePath(employeeHost) + "/" + employeeId;
    return webClientHelper.performGetToMono(URI.create(url), null, EmployeeModel.class);
  }
 
  @PostMapping
  public Mono<EmployeeModel> saveEmployee(@RequestBody EmployeeModel employeeModel){
    return webClientHelper.performPostToMono(URI.create(ApiPaths.getEmployeePath(
employeeHost)), employeeModel,
        EmployeeModel.class);
  }
...
}
Update ve Delete için şöyle yaparız
@PutMapping
public Mono<EmployeeModel> updateEmployee(@RequestBody EmployeeModel employeeModel){
  return webClientHelper
    .performPutToMono(URI.create(ApiPaths.getEmployeePath(employeeHost)), employeeModel,
      EmployeeModel.class);
  }
@DeleteMapping("/{id}")
public Mono<EmployeeModel> deleteEmployee(@PathVariable("id") Long employeeId){
  String url = ApiPaths.getEmployeePath(employeeHost) + "/" + employeeId;
  return webClientHelper.performDeleteToMono(URI.create(url),null, EmployeeModel.class);
}

Hiç yorum yok:

Yorum Gönder