You are currently viewing Building Microservices with Spring Boot and Eureka

Building Microservices with Spring Boot and Eureka

Spring Cloud Eureka is a service registry that allows microservices to register themselves and discover other services in the system.

Prerequisites:

  1. Java Development Kit (JDK) installed (at least version 8)
  2. Maven installed
  3. IDE (such as IntelliJ or Eclipse)
  4. Basic understanding of Spring Boot and microservices architecture

Step 1: Create a Spring Cloud Eureka Server

Create a new Spring Boot project for the Eureka server:

# Using Spring Initializer (https://start.spring.io/)
Dependencies: Eureka Server

Add the following configuration to application.properties:

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

This configuration ensures that the Eureka server does not try to register itself with itself.

Step 2: Create Microservice 1

Create a new Spring Boot project for the first microservice:

# Using Spring Initializer (https://start.spring.io/)
Dependencies: Web, Eureka Discovery

Add the following configuration to application.properties:

# application.properties
spring.application.name=microservice1
server.port=8081
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/

This configuration registers Microservice 1 with the Eureka server.

Step 3: Create Microservice 2

Create a new Spring Boot project for the second microservice:

# Using Spring Initializer (https://start.spring.io/)
Dependencies: Web, Eureka Discovery

Add the following configuration to application.properties:

# application.properties
spring.application.name=microservice2
server.port=8082
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/

This configuration registers Microservice 2 with the Eureka server.

Step 4: Create Controller for Microservices

In both microservices, create a simple controller to expose an endpoint. For example:

Step 5: Run the Applications

  1. Run the Eureka server application.
  2. Run Microservice 1 and Microservice 2 applications.

Step 6: Test the Setup

  1. Open your browser and navigate to http://localhost:8761/. You should see the Eureka server dashboard showing both microservices registered.
  2. Open a browser or use a tool like curl to access the endpoints:
  • Microservice 1: http://localhost:8081/hello
  • Microservice 2: http://localhost:8082/hello

You should receive responses from both microservices.

Congratulations! You have successfully set up Spring Cloud Eureka and two microservices. This basic setup can be extended to include additional features like load balancing, fault tolerance, and more, as needed for your microservices architecture.

Leave a Reply