Careeroza
Registering Eureka Clients
Add the Client Dependency
Add Eureka Discovery Client to product-service, order-service, user-service and payment-service. No annotation is needed: Spring Boot auto-registers the app when the starter is on the classpath.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>product-service application.yml
The spring.application.name becomes the service ID that others use:
application.yml
spring:
application:
name: product-service # the name in the registry
server:
port: ${PORT:8081}
eureka:
client:
service-url:
defaultZone: ${EUREKA_URL:http://localhost:8761/eureka/}
instance:
prefer-ip-address: true # register the IP, not the machine host nameExample output
INFO com.netflix.discovery.DiscoveryClient : DiscoveryClient_PRODUCT-SERVICE/10.0.0.11:product-service:8081: registering service... INFO com.netflix.discovery.DiscoveryClient : DiscoveryClient_PRODUCT-SERVICE/10.0.0.11:product-service:8081 - registration status: 204
Run Two Instances
Example
Start a second copy of product-service on another port. Both register under the same name:
PORT=9081 ./mvnw spring-boot:run
# ask Eureka for the registry (JSON)
curl -s -H "Accept: application/json" localhost:8761/eureka/apps/PRODUCT-SERVICEExample output
{
"application": {
"name": "PRODUCT-SERVICE",
"instance": [
{ "instanceId": "10.0.0.11:product-service:8081", "ipAddr": "10.0.0.11",
"port": { "$": 8081 }, "status": "UP" },
{ "instanceId": "10.0.0.11:product-service:9081", "ipAddr": "10.0.0.11",
"port": { "$": 9081 }, "status": "UP" }
]
}
}Looking Up Instances in Code
DiscoveryClient is the low-level API. You rarely need it (the load balancer uses it for you), but it is useful for debugging:
@RestController
@RequiredArgsConstructor
class DiscoveryDebugController {
private final DiscoveryClient discoveryClient;
@GetMapping("/debug/instances/{serviceId}")
List<String> instances(@PathVariable String serviceId) {
return discoveryClient.getInstances(serviceId).stream()
.map(i -> i.getUri().toString())
.toList();
}
}Example
curl localhost:8082/debug/instances/product-serviceExample output
["http://10.0.0.11:8081","http://10.0.0.11:9081"]