How to write a microservice that can make internal calls to other microservices.
In my last, I discussed Service Discovery In Microservice, and here is the third installment of the microservices communication series.
Let us now construct our client service, which we shall refer to as "employee service." Spring Initializer is being used to create our project. Choose Spring Boot Version, then add the "Spring Web" and "Eureka Discovery Client" requirements before generating as a Maven project:
Add the application name and Eureka details to the application.properties file.
Then, in the main application, add the @EnableEurekaClient annotation.
Client-side load balancing determines which instance to call (in the case of many end services running in the cluster that the client can call).
Netflix Eureka, which was later open sourced. Its dependent is bundled with the Eureka Discovery dependency. It integrates with Spring and distributes loads based on server health, region, and other factors.
We won't have to utilise Ribbon directly because it automatically combines RestTemplate, Zuul, Feign, and so on (we may say routing will occur).
We made RestTmplate ribbon aware by using @LoadBalanced.
Let's now create a Client-controller class that calls Employee Service inside.
We @Autowired the Ribbon-enabled RestTemplate and used it to invoke the Employee -Service in the preceding code. It's worth noting that we don't need to specify the hostname or the port anywhere.
Because Spring is registered with the Eureka server, it retains a list of all the services and their running instances locally. When we make a REST call like this to the employee-service (rather than giving a hostname and port), it substitutes the real endpoint URLs from the previously stored list and then makes the REST call.
Of course, the saved list of services and their running instances is updated on a regular basis. The best part is that we don't have to worry about any of this because Spring handles everything inside.
Now, use your favourite browser or postman to call the client-service endpoint.
http://localhost:8050/clientService, and you'll get something like this in return.
Conclusion:
We've gone through how to use Spring Cloud Eureka for service discovery in a microservice/cloud context in this article. We built two simple REST services (Employee-Service and Clint-Service) that communicate with each other without using any hardcoded hostnames or ports while making REST calls.