Service Discovery
In a microservices world, services change IP addresses dynamically (scaling up/down). Hardcoding URLs (http://localhost:8081) is impossible in production. We need a “Phonebook”.
1. Netflix Eureka Server
Eureka is a Service Registry. Services register themselves here, and other services query it to find them. Setup Eureka Server- Create a new Spring Boot project.
- Dependency:
spring-cloud-starter-netflix-eureka-server. - Annotation:
@EnableEurekaServer. - Configuration (
application.yml):
2. Eureka Client (The Microservice)
Now, let’s connect aUser Service to Eureka.
- Dependency:
spring-cloud-starter-netflix-eureka-client. - Configuration:
http://localhost:8761 to see it listed.
3. Service-to-Service Communication
How doesOrder Service call User Service without knowing the IP?
The Flow: Client-Side Load Balancing
In the old days (Hardware LB), the heavy lifting was done by a central F5/NGINX. In Microservices, the Client (Order Service) is smart.RestTemplate (Deprecated/Legacy)
USER-SERVICE in Eureka, gets a list of IPs, and uses Round Robin load balancing to pick one.
WebClient (Reactive & Modern)
The recommended way in modern Spring.Feign Client (Declarative)
The cleanest way. It looks like a JPA Repository but for HTTP calls.- Dependency:
spring-cloud-starter-openfeign. - Annotation:
@EnableFeignClients.
UserClient and call getUser(id). Spring handles the lookup, load balancing, and HTTP serialization!