How to create Service Registry/Discovery in Microservices


Service Discovery is a database used to keep track of the available instance of each microservices in an application. The service registry needs to be updated each time a new service comes online and whenever a service is taken offline or become unavailable.

How to Implement Service Registry and discovery

Now we are creating two  microservices EMPLOYEE-SERVICE and CUSTOMER-SERVICE and also create one SERVICE REGISTRY.

Step 1: Create new service for Service Registry with Eureka Server Dependency. Go to https://start.spring.io/  and create project with Eureka Server Cloud Dependency.

OR

Go to your pom.xml file and copy & paste given dependency.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

Add given property under properties in pom.xml file

<spring-cloud.version>2022.0.4</spring-cloud.version>

After closing dependencies tag press enter and add given code

<dependencyManagement>
   <dependencies>
     <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
     </dependency>
   </dependencies>
</dependencyManagement>

Step 2: EnableEurekaServer on mainClass of Service Registry Service

@EnableEurekaServer


Step 3: Go to application.properties file & disable Eureka Client on Service Registry.

server.port=8761
spring.application.name=SERVER-REGISTRY
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

Step 4: Go to Employee-Service microServices and add Eureka client Spring Cloud dependency.

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

Add given property under properties in pom.xml file

<spring-cloud.version>2022.0.4</spring-cloud.version>

After closing dependencies tag press enter and add given code

<dependencyManagement>
   <dependencies>
     <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
     </dependency>
   </dependencies>
</dependencyManagement>

Step 5: EnableDiscoveryClient on mainClass of EMPLOYEE-SERVICE Service

@EnableDiscoveryClient

Step 6: Go to application.properties file & add Client Server URL on EMPLOYEE-SERVICE.

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

Step 7: Implement same step 5,6,7 in CUSTOMER-SERVICE microservice as above.

Now your Service Registry is ready to use http://localhost:8761/

NOTE:- Eureka Server internally use LOADBALANCER.

Download Complete code Zip

That’s all.