Christopher Anabo
Christopher Anabo
Senior Tech Lead
Christopher Anabo

Notes

Spring Cloud Service Discovery with Netflix Eureka

Spring Cloud Service Discovery with Netflix Eureka

Overview

We will create three microservices for this Netflix Eureka example.

  1. Eureka Service Registry Server – This microservice will provide the service registry and discovery server.
  2. Student Microservice – Which will give some functionality based on Student entity. It will be a rest based service and most importantly it will be a eureka client service, which will talk with eureka service to register itself in the service registry.
  3. School Microservice – Same type as of Student service – only added feature is that it will invoke Student service with service look up mechanism. We will not use absolute URL of student service to interact with that service.

 

Here is the interaction diagram between above listed three services.

Pre Requisite

  • Java 1.8
  • Eclipse IDE
  • Spring cloud
  • Spring boot
  • Spring Rest
  • Maven

What is Netflix Eureka Server and Clients?

Microservices offer benefits like maintainability, scalability, and high availability over monolithic architectures, but they also pose challenges, particularly in managing individual service addresses. This complexity grows with the number of services and their dynamic nature. To address this, the concept of 'Service registration and discovery' is used, where a dedicated server maintains a registry of all deployed microservices. This server acts as a lookup service, allowing microservices to register and discover each other, providing metadata such as host and port. The server expects regular heartbeat messages from each instance, removing any that fail to send them, thus ensuring a stable ecosystem and eliminating the need for manual address maintenance, especially in dynamic cloud environments.

 

Eureka Service Registry Server

Follow these steps to create and run Eureka server.

Create Eureka Server

Create a Spring boot project from Spring Boot initializer portal with two dependencies i.e. Eureka server and Actuator.

Eureka Server Service Project Generation

 

Unzip and import the project into Eclipse as existing maven project. In this step, all necessary dependencies will be downloaded from maven repository.

Now open SpringEurekaServerApplication class that spring already has generated in the downloaded project and add the @EnableEurekaServerannotation on the class.

package com.example.howtodoinjava.springeurekaserver;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
 
@EnableEurekaServer
@SpringBootApplication
public class SpringEurekaServerApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringEurekaServerApplication.class, args);
    }
}

Build the project once again. With this annotation, this artifact will act like microservice registry and discovery server.

Server Configuration

Create one file called application.yml in the src\main\resources directory. Add these properties –

server:
  port: ${PORT:8761} # Indicate the default PORT where this service will be started

eureka:
  client:
    registerWithEureka: false #telling the server not to register himself in the service registry
    fetchRegistry: false
  server:
    waitTimeInMsWhenSyncEmpty: 0 #wait time for subsequent sync

Create another file called bootstrap.yml in the src\main\resources directory. Add these properties –

spring:
  application:
    name: eureka
  cloud:
    config:
      uri: ${CONFIG_SERVER_URL:http://localhost:8888}

Test Eureka Server

Start the application as spring boot application. Open browser and go to http://localhost:8761/, you should see the eureka server home page which looks like below.

Eureka Console Without Any Client

Please note that at this point no service is registered here which is expected and once we will spin up the client services, this server will automatically updated with the details of the client services.

Eureka Client – Student Service

Follow these steps to create and run Eureka client running student service.

Create Eureka Client Project

Create a Spring boot project from initializer portal with four dependencies i.e. Actuator, Web, Rest Repositories, Eureka Discovery. Give other maven GAV coordinates and download the project.

Eureka console with Student service registered

We will now verify that the /getStudentDetailsForSchool/{schoolname} endpoint is up and running. Go to browser and go to http://localhost:8098/getStudentDetailsForSchool/abcschool, it will give the Student details for a particular school abcschool.

package com.example.howtodoinjava.springeurekaclientschoolservice.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class SchoolServiceController {
 @Autowired
 RestTemplate restTemplate;

 @RequestMapping(value = "/getSchoolDetails/{schoolname}", method = RequestMethod.GET)
 public String getStudents(@PathVariable String schoolname) 
 {
  System.out.println("Getting School details for " + schoolname);

  String response = restTemplate.exchange("http://student-service/getStudentDetailsForSchool/{schoolname}",
        HttpMethod.GET, null, new ParameterizedTypeReference() {}, schoolname).getBody();

  System.out.println("Response Received as " + response);

  return "School Name -  " + schoolname + " \n Student Details " + response;
 }

 @Bean
 @LoadBalanced
 public RestTemplate restTemplate() {
  return new RestTemplate();
 }
}

This way we can get rid of specific service configuration and we can give the service look up responsibility to eureka server and rest template provided here. We can also apply load balancing (see @LoadBalanced annotation) here if the multiple instances are running for the same service.

The URL we have used is http://student-service/getStudentDetailsForSchool/{schoolname}. Clearly we are using only service name student-service in the place of host:port. This will be handled internally by spring framework, eureka server and rest template together.

Demo of Service Discovery and Calling

Now start the school service as well. All three services are started. Check the eureka server console. Bothe student and school services must be registered there.

School Service Response

Things to check if facing any error

  1. Annotations @EnableEurekaServer and @EnableEurekaClient are the heart of the application ecosystem. Without those two things will not work at all.
  2. Make sure at the time of starting the config client service, eureka server service is running already, otherwise it might take some time to register, which might create confusion while testing.

Summary

We saw how easily one can deploy service registry and discovery server as well as clients efficiently. Spring framework is maintaining lots of things internally. Here we are just using couple of annotations and very minimal configuration to achieve the whole things quickly.

That’s all about creating spring could eureka server and service registration for microservices. Please add comments if you have any difficulty executing this article. We will be happy to look into the problem.