2 Ocak 2020 Perşembe

SpringWebFlux WebClient Arayüzü

Giriş
Bu sınıf spring webflux projesine ait. Açıklaması şöyle.
Behind the scenes, WebClient calls an HTTP client. Reactor Netty is the default and reactive HttpClient of Jetty is also supported. Moreover, it's possible to plug other implementations of HTTP client by setting up a ClientConnector for WebClient.
Singleton
Açıklaması şöyle
Unlike RestTemplate, which was often instantiated per request or service, WebClient is designed to be used as a singleton. This means you should create a single instance of WebClient and reuse it across your application. This approach ensures efficient resource utilization and avoids the overhead of repeatedly creating and destroying WebClient instances.
Örnek
Şöyle yaparız
@Bean public WebClient.Builder webClientBuilder() { return WebClient.builder(); }
Kullanım
WebClient nesneyi yaratmak için iki tane yöntem var
1. WebClient.create() metodu ile bir WebClient nesnesi oluşturulur
2. WebClient.Builder.build() ile bir WebClient nesnesi oluşturulur

Daha sonra elimizdeki WebClient nesnesinin
delete()
get()
head()
options()
metodları kullanılarak bir WebClient.RequestHeadersUriSpec<?> nesnesi elde edilir.

veya
patch()
post()
put()
metodları kullanılarak WebClient.RequestBodyUriSpec nesnesi elde edilir.

WebClient Flux Dönüşümü yazısına bakabilirsiniz
WebClient Mono Dönüşümü yazısına bakabilirsiniz

Örnek
Şöyle yaparız
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

public ResponseEntity<List<CustomerClientResponse>> getCustomerListWithTotalPagesHeader(Integer page, Integer size) {
  return WebClient.create()
    .get()
    .uri(builder -> builder.path(...)
                    .queryParam("page", page)
                    .queryParam("size", size).build())
    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
    .retrieve()
    .toEntity(new ParameterizedTypeReference<List<CustomerClientResponse>>() {})
    .block();
}
create metodu
Netty kullanan bir WebClient nesnesi döndürür.

Örnek
Şöyle yaparız.
@GetMapping(path = "/streaming", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ResponseBody
public Flux<Something> streamSomething() {
  return WebClient.create()
    .get().uri("http://example.org/resource")
    .retrieve().bodyToFlux(Something.class)
    .delaySubscription(Duration.ofSeconds(5))
    .repeat();
}
create metodu - String
Netty kullanan bir WebClient nesnesi döndürür.

Örnek
Şöyle yaparız
WebClient client = WebClient.create("https://example.com");
get metodu
WebClient.RequestHeadersUriSpec nesnesi döner.

post metodu
Şöyle yaparız.
WebClient webClient = WebClient.builder().baseUrl(baseUrl).build();

webClient.post().uri(uri)
  .contentType(MediaType.APPLICATION_JSON_UTF8)
  .accept(MediaType.APPLICATION_JSON_UTF8)
  .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils
  .encodeToString((plainCreds)
  .getBytes(Charset.defaultCharset())))
  .body(BodyInserters.fromObject(body)).retrieve()
  .bodyToFlux(EmployeeInfo.class)
  .doOnError(throwable -> {
    ...
  }).subscribe(new Consumer<EmployeeInfo>() {
    @Override
    public void accept(EmployeeInfo employeeInfo) {
      ...
    }
}); 
Örnek
Şöyle yaparız
@RestController
@RequestMapping("/api")
public class WebClientController {

  @Autowired
  private WebClient webClient;

  @GetMapping("/posts/{id}")
  public Mono <Post> getPost(@PathVariable String id) {
    return webClient.get()
      .uri("/question/{id}", id)
      .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
      .retrieve()
      .bodyToMono(Post.class);
  }

  @GetMapping("/posts")
  public Mono<String> getPosts() {
    return webClient.get()
      .uri("/question/")
      .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
      .retrieve()
      .bodyToMono(String.class);
  }

  @PostMapping("/posts")
  public Mono <String> createPost(final Post post) {
    return webClient.post()
      .uri("/question/")
      .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
      .body(Mono.just(post), Post.class)
      .retrieve()
      .bodyToMono(String.class);
    }
}
timeout metodu
Örnek
Şöyle yaparız
return webClient()
  .get()
  .uri("https://www.google.com")
  .exchangeToMono(
    response -> {
      if (response.statusCode().equals(HttpStatus.OK)) {
        return Mono.just("OK");
      }
      return Mono.just("OK");
    })
  .timeout(Duration.ofMillis(500)); //Timeout specified here

Hiç yorum yok:

Yorum Gönder