In my previous microservice article I have explained how one microservice can communicate with another microservice. In this article , we'll get introduced to client-side service discovery and load balancing via Spring Cloud Netflix Eureka.
Microservice architecture we have many small applications deployed separately and they often need to communicate with each other. Specifically, when we say client service, we mean a service that needs to make REST calls to some other end service.
The problem in this type of architecture is how the client service finds all of its end services. We could hardcode the hostname/port in some property file, but this isn't always practical or feasible in a cloud environment.
There could be any number of microservices, and it's time and resource-consuming to hard-code when there's an uncertain amount of them, and when their locations may change.
To further add to the complexity, services could have multiple instances of themselves (based on the load). Which instance will actually serve the response could be challenging as we want to have equal load distribution.
Netflix Eureka
Netflix Eureka is a lookup server (also called a registry). All the microservices in the cluster register themselves to this server.
When making a REST call to another service, instead of providing a hostname and port, they just provide the service name.
The actual routing is done at runtime along with equally distributing the load among the end services. There are other service discovery clients like Consul,
Zookeeper etc, but we will be using Eureka in this article.
To understand this concept we will be building three services in our example:
- Eureka Server: acts as a service registry.
- Employee Service: a simple REST service that provides Employee information.
- Recommendation Service: a simple REST service but it internally calls the Employee Service to complete its requests.
Eureka Server Setup:
The best way to start with a skeleton project is to use Spring Initializr. Select your preferred version of Spring Boot and add the "Eureka Server" dependency and generate as a Maven project.
To make a Eureka server, all we need to do is add the @EnableEurekaServer
annotation to our main class:
We will be running the server on port 8761
, which is the recommended port by the Spring team. So in application.properties
we'll add:
To test this endpoint, navigate your browser to http://localhost:8761/
Part2:
Employee Service: Read this article for how to setup end service called Employee service and all you need to do is follow below steps.
summary
- Model class
- Controller class
- Main application
- application.properties