Java Microservices Interview Questions for Intermediate

14. What is WebClient and How Java Microservices Communicate using WebClient?

An interface called WebClient represents the primary access point for web requests. It is also known as Reactive Web Client that is introduced in Spring 5. The new client is a non-blocking, reactive solution that works over HTTP/1.1 protocol. Also, it is the replacement of classic RestTemplate. We can use the WebClient for Java Microservices Communication by the following approach.

Add this dependency to the pom.xml file:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

After adding this library, create a Bean for the WebClient in the configuration file like below:

@Bean
public WebClient webClient() {
return WebClient.builder().baseUrl(addressBaseUrl).build();
}

After creating Bean, it is ready for use in the Service Class file. We can refer the below code:

@Service
public class EmployeeService {


// More Code Here


// -------------

@Autowired
private WebClient webClient;

public EmployeeResponse getEmployeeById(int id) {


// More Code Here

// --------------


// Using WebClient
AddressResponse addressResponse = webClient.get().uri("/address/" + id).retrieve().bodyToMono(AddressResponse.class).block();
employeeResponse.setAddressResponse(addressResponse);

return employeeResponse;
}

}

For more details please refer to this article: Spring Boot Microservices Communication using WebClient with Example

15. What is RestTemplate and How Java Microservices Communicate using RestTemplate?

The RestTemplate is a synchronous REST client that performs HTTP requests by using a simple API of template style.

  • This is a synchronous client and it is designed to call the REST services.
  • RestTemplate class plays a very major in Spring Boot Microservices Communication.

We can use RestTemplate for Java Microservices Communication by the following approach:

Microservices can communicate using RestTemplate.getForObject() method. Syntax of RestTemplate.getForObject() method is given below.

@Nullable
public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
return this.execute(url, HttpMethod.GET, requestCallback, responseExtractor, (Object[])uriVariables);
}

For more details please refer to this article: Spring Boot Microservices Communication using RestTemplate with Example

16. What is FeignClient and How Java Microservices Communicate using FeignClient?

FeignClient is known as Spring Cloud OpenFeign.

  • It is a declarative REST Client in Spring Boot Web Application. Declarative REST Client means to specify the client specification as an Interface and spring boot will take care of the implementation.
  • With the help of FeignClient, writing web services is very simple.
  • It is mostly used to consume REST API endpoints exposed by third parties or microservices.

We can use FeignClient for Java Microservices Communication by the following approach:

Add this dependency to the pom.xml file.

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

After adding the library, add this @EnableFeignClients annotation to the main Application file as below:

@SpringBootApplication
@EnableFeignClients
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

Create an Interface and define it with @FeignClient annotation and declare calling method as below:

@FeignClient(name = "giveHereServiceName", url = "provideUrlHere", path = "provideContextPathHere")
public interface AddressClient {

@GetMapping("/address/{id}")
public ResponseEntity<AddressResponse> getAddressByEmployeeId(@PathVariable("id") int id);

}

Now it is ready to be used in the service class file. You can see the below code:

@Service
public class EmployeeService {


// More Code Here


// -------------

// Spring will create the implementation
// for this class
// and here it will insert the bean (proxy) .
@Autowired
private AddressClient addressClient;

public EmployeeResponse getEmployeeById(int id) {

// More Code Here

// Using FeignClient
ResponseEntity<AddressResponse> addressResponse = addressClient.getAddressByEmployeeId(id);
employeeResponse.setAddressResponse(addressResponse.getBody());

return employeeResponse;
}

}

For more details please refer to this article: Spring Boot Microservices Communication using FeignClient with Example

17. How Client Side Load Balancing Happens in Java Spring Boot Microservices?

When a load balancer put on the client side along with assigning load balancing responsibilities to the client, this is called Client-Side Load Balancing. Spring Cloud LoadBalancer is one of the most popular client-side load balancers offered by Spring Cloud.

Spring Cloud LoadBalancer can be used for Client Side Load Balancing in Microservices by the following approach:

Add the following dependencies to pom.xml file.

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

Client Side Load Balancing can be done with the help of LoadBalancerClient. We need to write the following logic in our client microservice in the Service class.

@Autowired
private RestTemplate restTemplate;

@Autowired
private LoadBalancerClient loadBalancerClient;

// Get ServiceInstance list using serviceId
ServiceInstance serviceInstance = loadBalancerClient.choose("ADDRESS-SERVICE");

// Read URI and add the path that returns url
String uri = serviceInstance.getUri().toString();

// Get metadata
String contextPath = serviceInstance.getMetadata().get("configPath");

// HTTP call and got Response data
AddressResponse addressResponse = restTemplate.getForObject(uri + contextPath + "/address/{id}", AddressResponse.class, id);

18. How Load Balancing Happens in Java Spring Boot Microservices using Netflix’s Ribbon?

Ribbon is a special load balancer provided by Netflix so that we do not have to create this load balancer or write any code to make this pattern possible. We can only use the Netflix Ribbon for having the client-side load balancing.

We can use Netflix’s Ribbon for Load Balancing in Microservices by the following approach

Add the following dependency in pom.xml file:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

Annotate your Feign Client interface with @RibbonClient. Refer to the below code snippet.

@FeignClient(name = "address-service", path = "/address-service")
@RibbonClient(name = "address-service")
public interface AddressClient {

@GetMapping("/address/{id}")
public ResponseEntity<AddressResponse> getAddressByEmployeeId(@PathVariable("id") int id);

}

Make the following changes to the application.properties file.

address-service.ribbon.listOfServers=http://localhost:8081, http://localhost:8082

For more details please refer to this article: Spring Boot Microservices – Load Balancing using Netflix’s Ribbon

19. How Eureka Server and Client Communicate with Each Other in Java Microservices?

Service discovery is one of the key issues in microservices-based architecture. The Eureka is Netflix service discovery, consists of a discovery server and a client. The server can be configured and deployed to maximize performance, with each server copying the status of registered services to the others.

Suppose, our discovery service is running on the port number 5000,

server.port=5000

Now if we run our microservice then we may get the “Connection refused” error. To fix this, we have to add the following line in the application.properties file of microservice.

eureka.client.service-url.defaultZone=http://localhost:5000/eureka/

This will fix our issue.

20. How to Develop API Gateway in Java Spring Boot Microservices?

We can develop API Gateway in Java Spring Boot Microservices by using Spring Cloud Gateway. Spring Cloud Gateway provides a library for creating API gateways over Spring and Java. It provides a flexible way to submit standards-based requests, while focusing on contextual issues such as security, resiliency, and monitoring Spring Cloud Gateway features some of the most important ones are:

  • It is Built on Spring Framework 5, Project Reactor, and Spring Boot 2.0
  • We can integrate the Circuit Breaker with the Spring Cloud Gateway.
  • We can integrate Spring Cloud DiscoveryClient.
  • Predicates and filters are specific to routes.
  • Path Rewriting.
  • It can match routes on any request attribute.

Java Microservices Interview Questions and Answers

Microservices, also called Microservices Architecture, is a software development approach that involves building large applications as a collection of small functional modules. This architectural approach is widely adopted due to its ease of maintenance and faster development process.

Microservices with the Spring Boot framework break down complex applications into smaller services, loosely coupled services, each focusing on a specific business capability. This architecture promotes agility, scalability, and resilience, leveraging technologies like Docker, Kubernetes, and RESTful APIs for seamless communication and deployment in distributed environments.

Here, in this Java Microservices Interview Questions we have gathered a list of the Top 30 Java Microservices Interview Questions with Answers that are commonly asked in recent interviews. Whether you are a fresher or an experienced professional with 2, 5, 8, or 10 years of experience, going through these microservices interview questions will help you prepare for your upcoming technical interviews and increase your chances of succeeding.

Table of Content

  • Java Microservices Interview Questions for Freshers
  • Java Microservices Interview Questions for Intermediate
  • Java Microservices Interview Questions for Experienced

Similar Reads

Java Microservices Interview Questions for Freshers

1. What are Microservices?...

Java Microservices Interview Questions for Intermediate

14. What is WebClient and How Java Microservices Communicate using WebClient?...

Java Microservices Interview Questions for Experienced

21. How to Register Java Microservices Using Netflix Eureka?...

Conclusion

Microservices are also highly beneficial for modern software development methods like DevOps and Agile. Adopting this approach helps in delivering large, complex applications promptly, frequently, and reliably....

Microservices Interview Questions – FAQs

What is the typical salary range for a microservices developer in USA?...

Contact Us