Implementation of Dynamic Service Discovery and Load Balancing with Consul

Below are the implementation steps of Dynamic Service Discovery and Load Balancing with Consul.

Step 1: Download and install the Consul using officical site and pull the image using below command.

docker pull consul:1.12.0

Output:


Running Consul Command:

docker run -d -p 8500:8500 --name=dev-consul consul:1.12.0

Output:


Consul Dashboard:


Step 2: Create a new Spring Boot project using Spring Initializr and include the required dependencies,

  • Spring Web
  • Spring Consul Discovery
  • Lombok
  • Spring DevTools

After the project creation done, the project structure will look like below:


Step 3: Open the application.properties file rename into application.yml and add the configuration for the consul management of the Spring Security application in the project.

spring:
application:
name: consul-demo-service
cloud:
consul:
host: localhost
port: 8500
discovery:
enabled: true
register: true
instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}


Step 4: Create the Controller class.

We will create the ExampleController class that will create the secure REST API of the spring project.

Go src > org.example.springservicediscoveryconsul > controller > ExampleController and put the below code.

Java
package org.example.springservicediscoveryconsul.controller;

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

@RestController
public class ExampleController {

    @GetMapping("/greet")
    public String greet() {
        return "Hello from Consul-discovered service!";
    }
}


Step 5: Main Class (No Changes are required)

Go src > org.example.springservicediscoveryconsul > SpringServiceDiscoveryConsulApplication and put the below code.

Java
package org.example.springservicediscoveryconsul;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringServiceDiscoveryConsulApplication {

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

}


pom.xml file:

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.example</groupId>
    <artifactId>spring-service-discovery-consul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-service-discovery-consul</name>
    <description>spring-service-discovery-consul</description>
    <properties>
        <java.version>17</java.version>
        <spring-cloud.version>2023.0.1</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


Step 6: Run the Application

Now, we will run the application then it will start at port 8080.


Again run the Consul Using the below command:

docker run -d -p 8500:8500 --name=dev-consul consul:1.12.0

Output:


Greet Endpoint:

http://localhost:8080/greet

Output:

This example demonstrates the approach covers the essential aspects of the Consul for the dynamic service discovery and load balancing and it includes the practical example to help you get started immediately of Spring Boot application.



Dynamic Service Discovery and Load Balancing with Consul

Consul was developed by HashiCorp and it is a powerful tool that serves as the service mesh solution providing a full-featured control plan with service discovery, configuration, and segmentation functionality. These features can allow the distributed services to communicate with each other in the dynamic and efficient manner, adapting to the constantly changing conditions of the cloud-based environment. Service discovery can help the services find the each other and load balancing distributes the client requests across multiple instance of the service and improving the responsiveness and availability of the applications.

Service Discovery:

In the microservice architecture, services need to communicate with each other. However, managing the network locations (IP address and ports) of the service instance manually is impractical in the dynamic enviornments where the instances are constantly being created and destroyed. Consul can automate this process by allowing services to register themselves and discover the other services via a central registry.

Load Balancing:

Loan balancing can improves the distribution of the workloads across the multiple computing resources. In the context of Consul, it can dynamically adjust the traffic distribution based on the health and availability of the services instances. It can ensures that no single instance is overwhelmed which enhances the reliability and efficiency of the overall system.

Key Terminologies:

  • Agent: The Consul agent is a daemon that runs on the every node in the Consul cluster. Agents can run in the either server or client mode. Each Consul agent maintains its own local state and the set of the services and checks, participates in the consensus and helps in forwarding the queries to appropriate nodes.
  • Server: Servers are the backbone of the Consul cluster. It can perform the cricitical tasks like maintaining the cluster state, processing queries and handling all write operations. The small number of the servers, typically 3 or 5, is enough to the efficiently manage the large number of services across the different nodes.
  • Client: Client is the type of the Consul agent that forwards all RPCs to the server. Clients are lightweight agents that must be installed on the every machine that is part of the service discovery mechanism. It can manages the local node status and join the services and checks.
  • Consensus Protocal: It can uses the Raft consensus protocal to manage the highly available replicated the log that ensures consistency across all the servers in the cluster. This protocal can helps in the handling failures and leader election transparently.
  • Service Discovery: It is the process through which services register with Consul and it allowing the others to discovery them using the Consul API. It can helps the decouple service addresses from the application code, making it easier to scale dynamically.
  • Service Mesh: Consul provides the complete service mesh solution that provides the service to service connection authorization and encryption, obervability and control the across services without requring changes to the service code.

Similar Reads

Implementation of Dynamic Service Discovery and Load Balancing with Consul

Below are the implementation steps of Dynamic Service Discovery and Load Balancing with Consul....