6 September 2023
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.
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:
This is in contrast to monolithic architectures where all components are part of a single unit.
Microservices bring several advantages compared to monoliths:
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.
Spring Boot is an excellent framework for building microservices. Here are some key reasons:
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.
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:
For dependencies, select:
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 the generated project into your IDE as a Maven project.
For example, in Eclipse:
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.
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 the authentication service by calling its /login
endpoint:
$ curl localhost:8080/login
You should receive the "login" response. Our first microservice is ready!
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.
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.
Again generate a new Spring Boot project, this time adding:
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’.
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.
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.
Generate another Spring Boot project and include:
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.
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
.
Spring Cloud Config provides a centralized configuration server for managing service configurations across environments.
Again generate a Spring Boot project, now with:
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.
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.
In this step-by-step guide you built a set of microservices using Spring Boot and Spring Cloud:
These components provide a foundation for implementing a full microservices architecture.
Key takeaways include:
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.
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.
CONTACT
+44 (0)20 8446 7555
Copyright © 2024 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