Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Service Discovery and Registration with Eureka in Spring Cloud

Tech 1

Eureka is a REST-based service governence framework open-sourced by Netflix, designed for service registration, discovery, and location within cloud environments. The system is divided into two core components: Eureka Server and Eureka Client.

  1. Eureka Server: Acts as the registry center, managing the registration data of service instances. Upon initialization, a service registers its metadata (such as IP and port) with the server. The server continuously monitors these entries via heartbeats; if an instance fails to send a heartbeat within a specified timeframe, it is evicted from the registry to maintain accuracy and availability.
  2. Eureka Client: A module integrated into both providing and consuming services. Providers register their existence with the server at startup, while consumers query the server to locate available providers. The client also periodically fetches the latest registry updates to detect new or defunct instances dynamically.

Provider and Consumer Roles

Service Provider: A service that exposes APIs for other microservices to invoke during a business workflow. Service Consumer: A service that initiates calls to other microservices to fulfill a business requirement.

These roles are strictly contextual. If Service A invokes Service B, and Service B subsequently invokes Service C:

  • In the A-B interaction, A is the consumer and B is the provider.
  • In the B-C interaction, B acts as the consumer while C serves as the provider.

Consequently, Service B functions simultaneously as both a provider and a consumer depending on the transaction context.

Eureka Architecture and Mechanics

How does a consumer discover a provider's address?

  • Provider instances register their network coordinates with Eureka Server upon bootstrapping (Service Registration).
  • Eureka Server maintains a mapping of service identifiers to instance addresses.
  • Consumers query the server using the service identifier to retrieve the address list (Service Discovery).

How does a consumer select a specific instance among multiple providers?

  • The consumer applies a load balancing algorithm to the fetched instance list.
  • A remote procedure call is then executed against the chosen instance.

How does a consumer know if a provider instance is still active?

  • Provider instances dispatch periodic heartbeat requests (default interval is 30 seconds) to Eureka Server.
  • If heartbeats cease beyond a configured threshold, the server identifies the instance as compromised and evicts it from the registry.
  • Subsequent discovery requests from consumers will naturally exclude the failed instance.

Load Balancing Concepts

Load balancing distributes network traffic across multiple computing resources to maximize throughput, minimize latency, and prevent resource overload. Distribution follows predefined algorithms to ensure equitable workload handling.

Consider an e-commerce platform experiencing high traffic. To manage concurrent users, the backend is scaled across multiple servers hosting identical application data. When a client requests a product page, the request first hits a load balancer (such as Nginx). Using a Round Robin strategy, the balancer routes the initial request to Server A, the second to Server B, and the third to Server C, distributing the operational load evenly. Should Server B crash or become overwhelmed, the load balancer detects the failure and redirects subsequent traffic to the surviving nodes, preserving system availability.

Configuring Eureka Server

Dependency Injection

Include the Spring Cloud Eureka Server starter in your project:

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

Main Application Class

Create the bootstrap class and apply the @EnableEurekaServer annotation to activate the registry capabilities:

package com.example.registry;

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

@SpringBootApplication
@EnableEurekaServer
public class ServiceRegistryApp {
    public static void main(String[] args) {
        SpringApplication.run(ServiceRegistryApp.class, args);
    }
}

Configuration File

Define the application.yml settings:

server:
  port: 8761
spring:
  application:
    name: discovery-server
eureka:
  client:
    service-url: 
      defaultZone: http://localhost:8761/eureka/

If startup fails due to JDK compatibility issues, enforce Java 8 compilation in your pom.xml:

<properties>
    <java.version>1.8</java.version>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
</properties>

Launch the application and navigate to http://localhost:8761 in a browser to verify the dashboard.

Registering a Service Provider

Dependency Injection

Add the Eureka Client dependency to the provider's pom.xml:

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

Configuration File

Update the provider's application.yml with the application alias and Eureka Server coordinates:

spring:
  application:
    name: user-service-api
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

Refresh the Eureka dashboard to view the newly registered service.

Scaling Provider Instances

To simulate horizontal scaling, duplicate the provider's run configuration in your IDE. Configure the secondary instance to run on a distinct port (e.g., 8011 alongside the original 8010). Launching both instances will result in two active nodes registered under the user-service-api identifier, visible on the Eureka dashboard.

Service Discovery and Consumption

Dependency Injection

Since registration and discovery are both handled by the Eureka Client, add the same client dependancy to the consumer's pom.xml:

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

Configuration File

Provide the consumer's identity and the Eureka Server URL in its application.yml:

spring:
  application:
    name: order-service-api
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

Fetching Instances and Load Balancing

To enable automatic service discovery and client-side load balancing, annotate the RestTemplate bean with @LoadBalanced inside the consumer's main configuration class:

Modify the remote invocation logic within the consumer (e.g., in an OrderManager class) to utilize the provider's service identifier instead of hardcoded IP addresses and ports. Spring Cloud intercepts the request, queries Eureka for user-service-api instances, and applies load balancing before executing the HTTP call.

Tags: Spring Cloud

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.