spring

Spring Cloud Eureka Server Tutorial

Welcome readers, in this tutorial, we will explore an interesting Spring Cloud component known as Eureka for service registry and discovery.

1. Introduction

  • Spring Boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
  • It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or Undertow). Thus, no need to deploy the war files
  • It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them in the application
  • It helps in removing the boilerplate code, extra annotations, and xml configurations
  • It provides a powerful batch processing and manages the rest endpoints
  • It provides an efficient jpa-starter library to effectively connect the application with the relational databases
  • It offers a Microservice architecture and cloud configuration that manages all the application related configuration properties in a centralized manner.

1.1 Eureka Server

  • It is a Service Registration and Discovery application that holds the information about all the other microservices and is popularly known a Discovery server
  • Every Microservice registers itself into the Eureka server and is known as Discovery client
  • Eureka server knows the client microservices running status, port number, and IP address

Now, open the eclipse ide and let’s see how to implement this tutorial in spring boot. Do note, we will also create a client microservice and register the same on the discovery server.

2. Spring Cloud Eureka Server Tutorial

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven.

2.2 Project Structure

In case you are confused about where you should create the corresponding files or folder, let us review the Eureka server and Eureka client project structure of the spring boot application.

Spring Cloud Eureka Server - Application Structure
Fig. 1: Application Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring Cloud Eureka Server - Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

Spring Cloud Eureka Server - Project Details
Fig. 3: Project Details

Select the Maven Web App archetype from the list of options and click next.

Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in Fig. 5. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters for Eureka Server

Click on Finish and the creation of Eureka Server maven project is completed. Now repeat the above steps for the creation of Eureka Client maven project and input the details as shown in Fig. 6.

Fig. 6: Archetype Parameters for Eureka Client

Click on Finish and the creation of the maven project will be completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created for both projects. Let’s start building the application!

3. Creating a Eureka Server

Below are the steps involved in developing the Eureka or the Discovery server.

3.1 Eureka Server: Maven Dependencies

Here, we specify the dependencies for Spring Cloud and Discovery server. Maven will automatically resolve the other dependencies. The updated file will have the following code.

pom.xml

<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 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>jcg.tutorial</groupId>
	<artifactId>Springbooteurekaservertutorial</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	
	<name>Springboot eureka server tutorial</name>
	<url>http://maven.apache.org</url>
	
	<parent>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-parent</artifactId>
		<version>Angel.SR6</version>
	</parent>
	
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
		</dependency>
	</dependencies>
	
	<build>
		<finalName>Springbooteurekaservertutorial</finalName>
	</build>
</project>

3.2 Eureka Server: Configuration File

Create a new yml file at the Springbooteurekaservertutorial/src/main/resources/ location and add the following code to it.

application.yml

## Application port no. ##
server:
  port: 7171
  
eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false

3.3 Eureka Server: Implementation Class

Add the following code the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.

Eurekaserverapplication.java

package com.eurekaserver;

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

@SpringBootApplication
// This annotation enables the Eureka server for listing the discovery client application on the registry server.
@EnableEurekaServer
public class Eurekaserverapplication {

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

4. Creating a Eureka Client

Below are the steps involved in developing the Eureka or the Discovery client.

4.1 Eureka Client: Maven Dependencies

Here, we specify the dependencies for Spring Cloud and Discovery client. Maven will automatically resolve the other dependencies. The updated file will have the following code.

pom.xml

<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 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>jcg.tutorial</groupId>
	<artifactId>Springbooteurekaclientutorial</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	
	<name>Springboot eureka client tutorial</name>
	<url>http://maven.apache.org</url>
	
	<!-- spring boot parent dependency jar -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.3.RELEASE</version>
	</parent>
	
	<!-- To import the spring cloud parent pom as well. -->
	<dependencyManagement>
		<dependencies>
			<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-parent -->
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-starter-parent</artifactId>
				<version>Greenwich.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<!-- spring boot web mvc jar -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
			<version>1.4.6.RELEASE</version>
		</dependency>
	</dependencies>
	
	<build>
		<finalName>Springbooteurekaclientutorial</finalName>
	</build>
</project>

4.2 Eureka Client: Configuration File

Create a new properties file at the Springbooteurekaclientutorial/src/main/resources/ location and add the following code to it.

application.properties

## Application port no. ##
server.port=8181

## Specifying the application name. Using this name the client application gets registered in eureka server.
spring.application.name=greetings

## Specifying the url on which the eureka server is up and running. ##
eureka.client.serviceUrl.defaultZone=http://localhost:7171/eureka/

4.3 Eureka Client: Implementation Class

Add the following code the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.

WelcomeApp.java

package com.eurekaclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
// This annotation is used to register the application on the eureka server (i.e. the registry server).
@EnableDiscoveryClient
public class WelcomeApp {

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

4.4 Eureka Client: Controller Class

Add the following code to the controller class. Please note, this controller class for testing purpose only and developers can access it via the following link – http://localhost:8181/greet/welcome/{localeId}.

Greetingsctrl.java

package com.eurekaclient.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

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

@RestController
@RequestMapping(value= "/greet")
public class Greetingsctrl {
	// Greetings map.
	static Map<String, String> greetings;
	// Initialize the greetings map at the application start-up.
	static {
		greetings = new HashMap<String, String>();
		greetings.put("fr", "BONJOUR");
		greetings.put("es", "HOLA");
		greetings.put("de", "GUTENTAG");
		greetings.put("it", "CIAO");
		greetings.put("hi", "नमस्ते");
		greetings.put("en", "GOOD MORNING");
	}

	@GetMapping(value= "/welcome/{localeId}")
	public String getGreetings(@PathVariable(name= "localeId") String langCode) {
		System.out.println("Fetching greetings type for locale id= " + langCode);
		String msg = greetings.entrySet().stream().filter((code) -> langCode.equalsIgnoreCase(code.getKey()))
				.map(langName -> langName.getValue()).collect(Collectors.joining());
		return msg;
	}
}

5. Run the Applications

As we are ready with all the changes, let us compile the projects and run the applications as a java project.

  • Right click on the Eurekaserverapplication.java class, Run As -> Java Application. The Eureka server will be started on the 7171 port
  • Right click on the WelcomeApp.java class, Run As -> Java Application. The client microservice will be started on the 8181 port

Developers can debug the example and see what happens after every step. Enjoy!

6. Project Demo

Now hit the following url on your favorite browser and developers will see the Eureka Server page.

http://localhost:7171/
Fig. 7: Eureka Server Page

Developers can see here that the client microservice is registered with the server under the name – GREETINGS. In case the developers forget to name the client microservice, then the client application gets registered as UNKNOWN. That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

7. Conclusion

In this section, developers learned how to create a Eureka Server and Client application with spring boot. Developers can download the sample application as an Eclipse project in the Downloads section.

8. Download the Eclipse Project

This was an example of implementing the Eureka Server and Client application with spring boot.

Download
You can download the full source code of this example here: Spring Cloud Eureka Server Tutorial

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
manish baranwal
manish baranwal
4 years ago

I have java based configuration for spring rest. How i should use @EnableDiscoveryClient.

@EnableDiscoveryClient
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {“com.slb.sis.ps.services.topic.controller”,
“com.slb.sis.ps.services.topic.advice”,”com.slb.sis.ps.services.filter”,”com.slb.sis.ps.authorization.service”})
public class TopicServiceWebConfig {

}

i have application.properties
spring.application.name=prosource-topic-service

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka
eureka.client.registerWithEureka=true
eureka.client.fetchRegistry=true

But i am unable to register this with eureka server.

Back to top button