CUSTOMISED
Expert-led training for your team
Dismiss
How to Build Microservices with Spring Boot Step-by-Step Guide

6 September 2023

How to Build Microservices with Spring Boot Step-by-Step Guide

Building an application using microservices and Spring Boot offers a flexible way to develop complex systems. Compared to monolithic architectures, microservices provide benefits like independent scaling, easier maintenance and improved fault isolation.

This material is taken from JBI Trainings Spring Boot Microservices course the perfect solution if you are looking to train as an individual or a team. 

In this step-by-step guide, you’ll learn how to develop microservices using the popular Spring Boot framework. We’ll cover key concepts like creating standalone Spring Boot services, containerization with Docker and managing configuration.

You’ll build a simple microservices application that handles user management functionality. It will have separate services for authentication, account management and profile administration. By the end, you’ll have the knowledge to develop production-ready microservices with Spring Boot.

What Are Microservices?

Before diving into the tutorial, let’s clarify what exactly microservices architecture entails.

Microservices, or microservice architecture, is an approach to building an application as a suite of small, autonomous services. Each service runs in its own process and communicates with other services via HTTP APIs or messaging.

Services are built around business capabilities and independently deployable. For example, a user management microservice handles user accounts and profiles. A product catalog service stores product data and inventory.

Some key characteristics of microservices:

  • Independently deployable, upgradeable and scalable
  • Loosely coupled and communicate via APIs
  • Organized around business domains or capabilities
  • Owned by small teams

This is in contrast to monolithic architectures where all components are part of a single unit.

Microservices bring several advantages compared to monoliths:

  • Independent scaling: Scale only services that need it
  • Easier maintenance: Modify services without affecting others
  • Fault isolation: Failure in one service doesn’t break the entire app
  • Flexible tech stacks: Mix of languages and databases
  • Faster release cycles: Continuous delivery and deployment

Of course, microservices also come with increased complexity. Challenges include distributed coordination, testing and network latency.

However, for complex and evolving applications, adopting a microservice architecture can deliver significant long-term productivity and velocity benefits.

Why Use Spring Boot for Microservices?

Spring Boot is an excellent framework for building microservices. Here are some key reasons:

  • Simplified setup: Convention over configuration and starter dependencies get you up and running quickly
  • Embedded server: Run services with Tomcat, Jetty or Undertow included
  • Spring capabilities: Build on Spring Framework strengths like dependency injection and declarative programming
  • Management: Actuator for monitoring service health and metrics
  • Cloud native: Designed for cloud platform deployment, configuration and scale

By providing a solid foundation to get a microservice running quickly, Spring Boot allows you to focus on business logic. The integrated application server, opinionated approach to configuration, and production-ready features make it an ideal choice.

In this tutorial, you’ll use Spring Initializr to generate a basic Spring Boot project. Then extend it to implement the microservices application.

Generate the Spring Boot Project

We'll use the Spring Initializr tool to generate our base Spring Boot project. This provides a simple way to configure an app with useful defaults and dependencies.

Go to the Initializr and enter these details:

  • Project: Maven Project with Java
  • Language: Java
  • Spring Boot: 2.5.0
  • Group: com.example
  • Artifact: user-management
  • Name: user-management
  • Description: Microservices with Spring Boot
  • Packaging: Jar
  • Java: 8

For dependencies, select:

  • Spring Web
  • Spring Boot Actuator
  • Spring Configuration Processor

and click GENERATE.

This will download a zip file with a configured Spring Boot project containing the dependencies above. Extract it to a folder on your system.

Import into IDE

Import the generated project into your IDE as a Maven project.

For example, in Eclipse:

  • File > Import > Existing Maven Projects
  • Select the folder containing the extracted project
  • Complete the import wizard

The project contains a simple Spring Boot application with UserManagementApplication class containing the main() method to launch the app.

We'll use this as the starting point to build our microservices next.

Create the Auth Microservice

Let's create a microservice called auth-service that will handle user authentication functionality.

Under src/main/java create a new package called com.example.auth. Add a new class AuthServiceApplication with the following code:

package com.example.auth;

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

@SpringBootApplication
public class AuthServiceApplication {

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

This contains the standard Spring Boot application bootstrap configuration.

Next, create a REST controller called AuthController:

package com.example.auth;

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

@RestController
public class AuthController {

  @RequestMapping("/login")
  public String login() {
    return "login";
  }

}  

This implements a simple /login endpoint that responds with the text "login".

Now run the AuthServiceApplication main class to launch the service. By default it will run on port 8080.

Test Auth Service

Test the authentication service by calling its /login endpoint:

$ curl localhost:8080/login

You should receive the "login" response. Our first microservice is ready!

Containerize with Docker

Next, we'll package the auth service as a Docker image to prepare for cloud deployment.

First, create a Dockerfile in the project root:

FROM openjdk:8-jdk-alpine
EXPOSE 8080
COPY target/*.jar app.jar 
ENTRYPOINT ["java","-jar","/app.jar"]

This uses a minimal OpenJDK 8 base image, exposes port 8080, copies the built JAR file into the container and starts it.

Now build the Docker image:

$ docker build -t auth-service .

Once built, you can run the auth-service container:

$ docker run -p 8080:8080 auth-service

The service should again be available on http://localhost:8080/login.

This completes the authentication microservice. Follow similar steps to create additional services for the other features like accounts and user profiles.

Implement Service Discovery

As the number of services grows, we need a way to track and discover them. Spring Cloud Netflix Eureka can provide this service registry and discovery function.

Create Eureka Server

Again generate a new Spring Boot project, this time adding:

  • Eureka Server
  • Actuator

Call the main class EurekaServer.

Annotate it with @EnableEurekaServer to indicate it will be the registry/discovery service.

@EnableEurekaServer
@SpringBootApplication
public class EurekaServer {

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

With this service running, other application can now register with it to be ‘discovered’.

Register Microservices

Modify the auth-service to register itself with Eureka on startup.

Add Eureka Discovery dependency to its pom.xml:

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

In AuthServiceApplication, add @EnableEurekaClient:

@EnableEurekaClient
@SpringBootApplication
public class AuthServiceApplication {

  //...
}  

Start the Eureka server, followed by the auth-service. The service should register itself with Eureka and appear on its dashboard at http://localhost:8761.

Do this for additional services to have them discoverable by other services.

Add an API Gateway

To consolidate access to the microservices, we'll add an API gateway. This provides a single entry point to the system and handles routing, security, monitoring among other cross-cutting concerns.

Create API Gateway

Generate another Spring Boot project and include:

  • Eureka Discovery Client
  • Zuul

Name the main class ApiGatewayApplication and annotate with @EnableZuulProxy to indicate it's a Zuul proxy:

@EnableZuulProxy
@EnableEurekaClient 
@SpringBootApplication
public class ApiGatewayApplication {

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

}

This simple gateway already proxies all microservices registered with Eureka without additional configuration.

Forward Requests

If needed, we can explicitly configure routes for services.

For example, forward /auth requests to the auth-service:

zuul:
  routes:
    auth-service:
      path: /auth/**
      serviceId: auth-service

With this gateway in place, clients can now access services via a single endpoint. For example, /auth/login will be proxied to the auth-service.

Manage Configurations

Spring Cloud Config provides a centralized configuration server for managing service configurations across environments.

Config Server

Again generate a Spring Boot project, now with:

  • Config Server
  • Eureka Discovery Client

Name the main class ConfigServer.

@EnableConfigServer
@EnableEurekaClient
@SpringBootApplication
public class ConfigServer {

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

@EnableConfigServer activates configuration server functionality.

For a Git backend, add spring.cloud.config.server.git.uri configuration property pointing to a Git repository containing config files.

Configure Clients

Client services need the Config Client dependency:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

Services can load application.yml from the config server by name:

spring:
  application:
    name: auth-service
  cloud:
    config:
      uri: http://configserver:8888
      fail-fast: true

Configuration is now externalized across all environments.

Wrap Up

In this step-by-step guide you built a set of microservices using Spring Boot and Spring Cloud:

  • Auth service - Handles authentication
  • Eureka server - Service registry for discovery
  • API gateway - Routes requests to services
  • Config server - Externalized configuration

These components provide a foundation for implementing a full microservices architecture.

Key takeaways include:

  • Spring Boot simplifies building standalone, production-grade services
  • Docker provides consistent containerization for deployment
  • Eureka enables registration and discovery of services
  • API gateways consolidate access and handle cross-cutting concerns
  • Spring Cloud Config externalizes configuration across environments

You now have the knowledge to start developing complex microservices systems with Spring Boot and Spring Cloud. Useful next steps would be adding database persistence, security, monitoring, and CI/CD pipelines.

I hope you found this guide helpful! Let me know if you have any other questions. Or check out our next article Securing Microservices with Spring Security or consider training on our Spring Boot Microservices course 

In the world of modern software development, Microservices Architecture stands as a pivotal paradigm for building scalable and maintainable applications. Explore our range of courses at JBI Training, each tailored to empower you with the skills to excel in the realm of microservices and software architecture.

  • Microservices Architecture: Delve into the core principles and practices of microservices architecture. Learn how to design, deploy, and manage microservices-based systems, fostering agility and scalability in your applications.
  • Micro Frontends: Explore the world of micro frontends, a complementary concept to microservices. Learn how to create modular frontend applications that align with the principles of microservices architecture, enhancing flexibility and maintainability.
  • Software Architecture: Deepen your understanding of software architecture principles. Gain insights into architectural patterns, design principles, and best practices that underpin successful software systems, including microservices.
  • AWS for Developers: Discover how to leverage AWS (Amazon Web Services) to support your microservices-based applications. Learn to deploy, scale, and manage microservices on AWS, harnessing the power of cloud computing for your development needs.

Enrol in these courses and empower yourself to navigate the dynamic world of microservices architecture and software development. Equip yourself with the tools and knowledge to design, build, and manage microservices-based systems that excel in scalability, flexibility, and performance.

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2023 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course