Hi guys,
Let’s see how we can call a microservice from an another microservice in a microservice architecture.
First, we need to inject a bean of WebClient which is load-balanced.
@Configuration
public class ProjectConfiguration {
@LoadBalanced
@Bean
public WebClient.Builder webClientLoadBalanced() {
return WebClient.builder().defaultHeaders(header -> header.setBasicAuth("username", "password"));
}
}
Next, we need to make a call using this bean. Consider that the microservice that needs to be called is “share-market-live” and the endpoint URI is “product/data”. Follow the comments in the code for more details.
@RequiredArgsConstructor
@Service
public class RestServiceImpl implements RestService {
@LoadBalanced
private final WebClient.Builder builder;
@Override
public Mono<String> sendSubscriptionNotificationToAffiliate(RequestBody obj) {
return builder.baseUrl("lb://share-market-live") // always use lb instead of http
.build()
.post() // http method
.uri("product/data") // The URI
.accept(MediaType.APPLICATION_JSON) // Media Type sent
.bodyValue(obj) // Request body
.retrieve()
.bodyToMono(String.class) // Expected data type
.doOnSuccess(s -> log.info("Success.")) // implementation on success
.doOnError(e -> log.error("Failed.", e)); // implementation on error
}
}
That’s it.
Feedback / comments are welcome.
Have a nice day ahead.
![]()
Leave a Reply