You are here
Home > java >

How to register & discover Microservices using Netflix Eureka?

How to register & discover Microservices using Netflix EurekaIn the series of Microservices Tutorial, we have already discussed on Microservices Architecture and Microservices in Java in a theoretical way. Now in this article, we will create an example of using Netflix Eureka in the context of Microservices. We will use Netflix Eureka to register & discover Microservices. In order to make intra-communication happen among multiple microservices, it is mandatory to register & discover them in the application. It is possible by using Netflix Eureka in our context of this article. Hence, we will talk about ‘How to register & discover Microservices using Netflix Eureka?’ in this article.

In order to make communication happen among all microservices in an application, there should be a common medium. Further, that common medium should have details of all microservices in the application. Whenever a microservice needs to communicate with other microservice, it should first connect with the common medium to discover the other microservice. However, in our context, this common medium is nothing but Eureka Server. All microservices will register with Eureka Server as a discovery client. When a microservice needs to communicate with the other microservice it will discover other microservice with the help of Eureka Server. Let’s discuss our topic ‘How to register & discover Microservices using Netflix Eureka?’ accordingly.

What Can You Expect from This Article as a Whole?

1) Why Netflix Eureka is required?
2) What is Netflix Eureka?
3) What is Service Registry in Microservices?
4) What is Service Discovery in Microservices?
5) How to create Eureka Server for service registry & discovery?
6) How to register & discover Microservices using Netflix Eureka?
7) How to discover a Microservice using Netflix Eureka?
8) What are the execution steps to run the application?
9) How to test the whole application?

What is Netflix Eureka?

Netflix is an organization who provides various open source projects. Eureka is one of those projects that is the most commonly used for service registry & discovery in the context of Microservices. We also call it Registry & Discovery Server. It holds the details of Microservices running (Service Instance). Every Microservice, must be registered with Eureka Server. Netflix is one of the leading organizations in open source Microservices libraries that works well with Spring Boot. Among the most common projects that we use in Microservices are Eureka, Ribbon, Hystrix, Zuul projects.

What is Service Registry in Microservices?

Service Registry is the process of registering a microservice with Eureka Server. In a nutshell, it acts as a kind of database which stores the details of all microservices involved in the entire application. However, this is also a regular Spring Boot application. In order to enable the service registry, we apply annotation @EnableEurekaServer on the top of the Application’s main class. Moreover, on using Spring Cloud’s annotation @EnableEurekaServer, other microservices can register here and communicate with each other via service discovery.

What is Service Discovery in Microservices?

Service Discovery is the process of discovering other microservices in the network to make intra-communication happen. However, a microservice first connects with Eureka to discover other microservice to make communicating with each other. Using Service Discovery, one microservice can connect with the other microservice via Eureka.

Software/Technology used in this Project ?

♦ STS (Spring Tool Suite) : Version-> 4.7.1.RELEASE
– Starter dependencies : Eureka Server, ‘Eureka Discovery Client’ and ‘Spring Web’
♦ JDK8 or later versions (Extremely tested on JDK8, JDK9 and JDK14)
♦ Spring cloud, Spring Boot, Spring Rest, Maven

How to create Eureka Server for service registry & discovery?

Creating a Eureka Server is itself similar to creating a Microservice. Moreover, it is just a Spring Boot Project that incorporates Spring Cloud’s Eureka Server dependency. In application.properties file we will have some specific properties that will indicate that this application/microservice is a Eureka server. In order to create Eureka Server follow the below steps.

Step #1: Create a Spring Boot Project

Here, we will use STS(Spring Tool Suite) to create our Spring Boot Project. If you are new to Spring Boot, visit Internal Link to create a sample project in spring boot. While creating a project in STS, add starter ‘Eureka Server’ in order to get features of it.

Step #2: Apply Annotation @EnableEurekaServer at the main class

In order to make your application/microservice acts as Eureka server, you need to apply @EnableEurekaServer at the main class of your application.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class SpringCloudEurekaServerApplication {

             public static void main(String[] args) {
                         SpringApplication.run(SpringCloudEurekaServerApplication.class, args);
             }
}

Step #3: Modify application.properties file

Add below properties in your application.properties file.

server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

eureka.client.register-with-eureka=false

Default value of property ‘eureka.client.register-with-eureka’ is true. Please note that this property is mandatory to include in Eureka Server in order to make its value as false. However, this is optional to add in case of other microservices/applications that are not Eureka server. Moreover, every microservice project is connected to Spring Cloud project that provides default value to true. Therefore, We should include ‘eureka.client.register-with-eureka=false’ for one time only in case of Eureka server as Eureka Server itself can’t be registered.

eureka.client.fetch-registry=false

This property indicates that Eureka Server is supported to fetch instance details of microservice to make intra-communication between microservices happen. If one microservice wants to communicate with another microservice by using Eureka then inside microservice we should add this property (eureka.client.fetch-registry) and set it to true. However, inside Eureka Server we should include this property with a value as false. However, Eureka server will never try to fetch registry as it is itself having a registry. Hence the value of this property in case of Eureka server will be false. Moreover, every microservice project is connected to Spring Cloud project that provides default value to true.

Default port for Eureka Server is 8761.

Details of use-case used in this Example

In order to demonstrate service registry & discovery using Eureka, Let’s consider an example of online shopping. We will create two microservices: Cart Service and Payment Service and register both of them with Eureka Server. We will register both services with Eureka so that they can communicate with each other and exchange data between them. Further, we will assume Cart Service as a provider application whereas Payment Service as a Consumer Application.

How to register a Microservice using Netflix Eureka?

In this section we will focus on Cart Service to illustrate the service registry feature.

Step #1: Create a Spring Boot Project as a Eureka Discovery Client

While creating Spring Boot Project in STS, add starter ‘Eureka Discovery Client‘ and ‘Spring Web’ in order to get features of it.

Step #2: Apply Annotation @EnableEurekaClient at the main class

In order to make your application/microservice acts as a Eureka discovery client, you need to apply @EnableEurekaClient at the main class of your application.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableEurekaClient
@SpringBootApplication
public class SpringCloudCartServiceApplication {

         public static void main(String[] args) {
                 SpringApplication.run(SpringCloudCartServiceApplication.class, args);
         }
}

Step #3: Modify application.properties file

Add the below properties in your application.properties file.

server.port=9009
spring.application.name=CART-SERVICE   
eureka.client.service-url.default-zone=http://localhost:8761/eureka         #Register with Eureka

As from the above property, spring.application.name=PAYMENT-SERVICE indicates the Service Id of the microservice. Further, ‘eureka.client.service-url.default-zone=http://localhost:8761/eureka’ indicates that this service is getting registered with the Eureka Server.

♥ Note : You need to keep different port numbers for each microservices involved in the application.

Step #4: Write a RestController to test the service

In order to test whether the service is working, let’s write a RestController as CartRestController.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@[email protected]("/cart")
public class CartRestController {

      @GetMapping("/getData")
      public String getCartData() {
                 return "Returning data from CART-SERVICE";
      }
}

How to discover a Microservice using Netflix Eureka?

By using DiscoveryClient we can get Service Instance details of microservice from Eureka Server using ServiceId as input. Once we get Service Instance data, then we can use HTTP Client: RestTemplate (C) to make an HTTP Request for Provider application. As aforementioned, we will create a Payment service in this section as a Consumer Application.

Step #1: Create a Spring Boot Project as a Eureka Discovery Client

While creating Spring Boot Project in STS, add starter ‘Eureka Discovery Client‘ and ‘Spring Web’ in order to get features of it.

Step #2: Apply Annotation @EnableEurekaClient at the main class

In order to make your application/microservice acts as a Eureka discovery client, you need to apply @EnableEurekaClient at the main class of your application.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableEurekaClient
@SpringBootApplication
public class SpringCloudPaymentServiceApplication {

          public static void main(String[] args) {
                    SpringApplication.run(SpringCloudPaymentServiceApplication.class, args);
          }
}

Step #3: Modify application.properties file

Below is the property file for our Payment Service.

server.port=8989
spring.application.name=PAYMENT-SERVICE
eureka.client.service-url.default-zone=http://localhost:8761/eureka

From the details of properties file, it is clear that the service is registered with Eureka Server and ready to be discovered by other service via Eureka server.

Step #4: Create a service Consumer class as CartRestConsumer

Let’s create a CartRestConsumer and discover Service Instance of Cart Service to communicate and get data. In order to do this, we will take help of DiscoveryClient.

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class CartRestConsumer {

        // autowire DisocveryClient
       @Autowired
       private DiscoveryClient client;

       public String getCartInfo() {
       // get ServiceInstance list using serviceId
       List<ServiceInstance> siList = client.getInstances("CART-SERVICE");

       // read manually one instance from index#0 
       ServiceInstance si = siList.get(0);

       // read URI and Add path that returns url
       String url = si.getUri() +"/cart/getData";

       // create object for RestTemplate
       RestTemplate rt = new RestTemplate();

       // make HTTP call and get Reponse data
       String response = rt.getForObject(url, String.class);

        // return response back to Consumer 
           return response;
       }
}

Step #5: Create a service Rest Controller as PaymentRestController

Here, create HAS-A relation between RestController and RestConsumer, then call Consumer method to get data from Cart microservice as below.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dev.erurekatest.consumer.CartRestConsumer;

@RestController
@RequestMapping("/payment")
public class PaymentRestController {

         @Autowired
         private CartRestConsumer consumer;  // HAS-A

         @GetMapping("/data")
         public String getPaymentData() {
                return "FROM PAYMENT-SERVICE : " + consumer.getCartData();
         }
}

How to execute and test the whole application?

Please follow below steps to test the whole application :

1) Start the Eureka Server
2) Start the Provider Application (CartService)
3) Start the Consumer Application (PaymentService)
4) Click on Payment Service link on Eureka screen
It will be like : http://192.168.0.7:8989/actuator/info
5) Modify URL path as: ‘/payment/data’ in place of ‘/actuator/info’ and hit Enter.
http://192.168.0.7:8989/payment/data

Finally, you will be able to see the expected output.

Conclusion

After going through all the theoretical & examples part of ‘How to register & discover Microservices using Netflix Eureka’, finally, we should be able to implement our first small microservice application. Of course, In this article we have thoroughly learned about the Service registry & Discovery features using Eureka. Similarly, we expect from you to further extend this example and implement it in your project accordingly. For further details on this topic you can also check spring.io article. Additionally, If there is any change in the future, we will update the article accordingly. Moreover, Feel free to provide your comments in the comments section.

 

close

2 thoughts on “How to register & discover Microservices using Netflix Eureka?

Leave a Reply

Top