// get example
public <T> Mono<T> get(String url, Class<T> responseType,String token) {
return webClient.get()
.uri(getUriBuilderURIFunction(url))
.header(MessageConst.AUTHORIZATION, MessageConst.BEARER +token)
.retrieve()
.bodyToMono(responseType)
.timeout(timeout)
.doOnSuccess(response -> log.info("Received successful response from GET {}", url))
.doOnError(error -> log.error("Error in GET request to {}: {}", url, error.getMessage()))
.retryWhen(
Retry.backoff(retry, Duration.ofSeconds(1)).filter(e->!e.getMessage().equals("401"))
.doBeforeRetry(retrySignal -> log.warn("Retrying GET request to {}", url))
)
.onErrorResume(this::handleError);
}
// post example
public <T> Mono<T> post(String url, Object body, Class<T> responseType,String token) {
return webClient.post().uri(getUriBuilderURIFunction(url))
.header(MessageConst.AUTHORIZATION, MessageConst.BEARER +token)
.bodyValue(body)
.retrieve()
.bodyToMono(responseType)
.timeout(timeout)
.doOnSuccess(response -> log.info("Received successful response from POST {}", url))
.doOnError(error -> log.error("Error in POST request to {}: {}", url, error.getMessage()))
.onErrorResume(this::handleError);
}
Exception handling
We can use reactive extreame to do the handling . We have certain methods like doOnError, doOnStatus, onErrorResume etc, using them we can define how we want to handle it.
Yes we can have multiple webclients bean present in the system. We need to create multiple beans with different bean names , then whenever required can use @Qualifier to inject the bean required.
// in configuratrion
@Bean
public WebClient userWebClient(){
return getBuilder(applicationProperties.getUserServiceUrl());
}
@Bean
public WebClient authWebClient(){
return getBuilder(applicationProperties.getAuthServiceUrl());
}
@Bean
public WebClient vendorWebClient(){
return getBuilder(applicationProperties.getVendorServiceUrl());
}
// usages
@Qualifier("vendorWebClient") WebClient webClient
Custom Headers and Query Parameters
Add custom headers and query parameters dynamically.