Search code examples
spring-cloudnetflix-eurekaservice-discovery

Communication between microservice using ServiceID from discovery instead of directory host?


I'm new microservice, I'm reading some example about discovery server, I see we can call another microservice api by using url like: http://inventory-service/api/inventory/{productCode}. "inventory-service" is a service instance I registered in discovery. So my question is what is the benefit of using serviceId intead of call directory host:port: http://localhost:9009/api/inventory/{productCode}.


Solution

  • Let asume you register inventory-service with Eureka server by configuring Eureka serviceUrl in src/main/resources/bootstrap.properties.

     spring.application.name=inventory-service
     eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
    

    Then build inventory-service and start 2 instances of it by running following commands.

     java -jar -Dserver.port=9001 target/inventory-service-0.0.1-SNAPSHOT-exec.jar
    
     java -jar -Dserver.port=9002 target/inventory-service-0.0.1-SNAPSHOT-exec.jar
    

    When you visit Eureka Dashboard http://localhost:8761/ you will see 2 instances of inventory-service registered.

    If you want to apply Client Load Balancing from your consumer application you would need a config like this:

     server.ribbon.listOfServers=localhost:9001,localhost:9002 
     server.ribbon.eureka.enabled=false
    

    If you want to start new instances you would need to register them in your consumer configuration.

    With ServiceID you don't have to worry about it, because all instances will register with the same identifier. It will be added automatically in the list of available servers.It is one of the advantages of using ServiceId instead hostname