0% found this document useful (0 votes)
25 views73 pages

M3 _ P1 - Introduction to Microservices Using Spring Boot

Uploaded by

thecloudonfire
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views73 pages

M3 _ P1 - Introduction to Microservices Using Spring Boot

Uploaded by

thecloudonfire
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 73

Implementation of

Microservices with Java


and Spring Boot
Contents
Module 3: Implementation of Microservices with Java and Spring Boot

● Spring Boot Basics: Configuration, auto-configuration, and understanding Spring


ApplicationContext.
● Service Discovery and Registration: Deep dive into Eureka and alternatives like
Zookeeper and Consul.
● API Gateway Functionality: Role of API gateways in routing, composition, and
protocol translation.
● Developing a Microservice in Spring Boot: Step-by-step guide to setting up a
microservice from scratch.
● Integrating Service Discovery: Hands-on implementation of Eureka client and
server configurations.
● Building and Consuming REST APIs: Creating secure and scalable APIs, handling
errors, and version management.
Spring Boot Basics
● Spring Boot is a Java-based framework used to create stand-alone,

production-ready Spring applications with minimal configuration.

● It’s built on top of the popular Spring Framework and is designed to

simplify the process of setting up and developing applications,

especially microservices.
● When building microservices or any other application, developers need

to set up various configurations, such as managing databases, security

settings, or even defining how the application will interact with different

services.

● In traditional Spring applications, this setup was often complex and

required a lot of manual configuration.

● Spring Boot reduces this complexity by providing default configurations

and making it easier to get started with minimal effort.


● Key Goals of Spring Boot

○ Simplified Configuration: Spring Boot reduces the amount of code you

need to write and configure manually. It comes with sensible defaults, so

you don’t have to worry about many details right from the start.

○ Standalone Applications: Spring Boot allows you to create applications

that can run independently without relying on an external web server like

Apache Tomcat. You can package your application as a Java archive file (JAR)

and run it directly with just one command.


● Production-Ready: With Spring Boot, you get built-in features for

logging, monitoring, and health checks, making it easier to deploy

applications in production.

● Microservices-Friendly: Spring Boot is particularly well-suited for

building microservices, where applications are broken down into

smaller, independently deployable components that can

communicate with each other.


Spring Boot Configuration
● Configuration in Spring Boot refers to the process of setting up and managing

various settings that your application needs to run.

● For instance, you might need to configure:

○ The port on which your application will run.

○ Database connection details (such as the database URL, username, and

password).

○ Custom application properties like security settings.

● Spring Boot makes configuration simple and flexible by allowing you to define

these settings in an easy-to-understand format.


Ways to Configure Spring Boot
1. Using application.properties or application.yml

○ The most common way to configure a Spring Boot application is by

using the application.properties or application.yml files.

○ These files store configuration settings as key-value pairs.

○ These files make it easy to configure things like server settings,

database connections, and more without having to write code for

it.
Example: application.properties Example: application.yml

server.port=8080 server:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb port: 8080

spring.datasource.username=root spring:

spring.datasource.password=secret datasource:

url: jdbc:mysql://localhost:3306/mydb

username: root

password: secret
2. Environment Variables

● Spring Boot can also pick up configuration from environment variables.

● This is useful when running applications in environments like Docker or Kubernetes,

where configuration might vary between environments.

● Example:

export SERVER_PORT=8081
3. Command-Line Arguments:

● You can override default configurations by passing them as command-line

arguments when starting your application.

● Example:

java -jar myapp.jar --server.port = 8082


Auto-Configuration in Spring
Boot
● One of the most powerful and convenient features of Spring Boot is

auto-configuration.

● Auto-configuration means that Spring Boot automatically sets up

many components for you based on what it detects in your project.


● How Does Auto-Configuration Work?

○ When you create a new Spring Boot application, you don’t need to manually

configure most of the infrastructure (like databases, web servers, or security

settings) yourself.

○ Spring Boot’s auto-configuration detects what you need based on:

■ What’s on the Classpath: If you add a database library (like H2 or MySQL)

to your project, Spring Boot will automatically configure a DataSource for you.
● Pre-set Defaults: Spring Boot provides default configurations that

work for most scenarios. For example, if you're building a web

application, Spring Boot will automatically configure a web server for

you.

● External Configuration: Auto-configuration works alongside your

application.properties or application.yml settings. If you provide

specific configuration in those files, Spring Boot will use that instead of

the defaults.
● Example of Auto-Configuration:

○ Let’s say you add Spring Data JPA (for database interaction) and H2

Database (an in-memory database) to your project dependencies.

○ Spring Boot will automatically configure:

■ A DataSource for connecting to the H2 database.

■ A JpaRepository for interacting with the database using Java objects.

■ An EntityManager for managing the database transactions.


Spring ApplicationContext
● The ApplicationContext in Spring is a core concept in both Spring Framework and

Spring Boot.

● It represents the container that holds and manages all the Spring Beans and

configurations.

● What is a Spring Bean?

○ A Bean is an object that Spring manages and configures for you.

○ When your application runs, Spring Boot automatically creates these beans and

makes them available to your application.

○ For example, a Controller or Service in a Spring Boot application is a bean that Spring

manages.
What is ApplicationContext?

● The ApplicationContext is the "heart" of the Spring Framework, and it manages all

the beans and their dependencies.

● When your application starts, the Spring ApplicationContext is created, and it:

○ Registers Beans: Spring identifies and registers beans in the context.

○ Manages Dependencies: If one bean depends on another (for example, a service

that needs a repository), Spring Boot automatically injects those dependencies.

○ Application Lifecycle: The context manages the lifecycle of the beans, ensuring

that they are created, initialized, and destroyed properly.


Understanding Dependency Injection:

● One of the main benefits of the ApplicationContext is Dependency Injection.

● This means that Spring Boot will automatically provide the required beans

to your components without you having to manually create them.

● For example, if your CustomerService depends on a CustomerRepository,

Spring Boot will inject the CustomerRepository into the CustomerService

when it creates the bean for you.


Spring Boot Starters:

● These are pre-built configurations that allow you to get started quickly with

various components like Spring Data JPA, Spring Security, or Spring Web.

Embedded Servers:

● Spring Boot comes with embedded servers like Tomcat or Jetty, so you don’t

need to install them separately.

● This makes running and testing your application locally very easy.
Spring Boot DevTools:

● Spring Boot offers a special module called DevTools, which helps developers with hot

reloads, automatic restarts, and faster development cycles.

Actuator:

● Spring Boot Actuator provides a set of built-in endpoints to monitor and manage

your application, such as /health for checking if your service is running properly

or /metrics for gathering runtime data.


Service Discovery and Service
Registry in Microservices
● Imagine you are writing microservices.

● Your company has adopted the microservices architecture you have

Address Service, Employee Service, Course Service, Student Service,

etc, etc.

● You have many spring boot applications and all the spring boot

application has been deployed into many different servers and you

might have thousands of applications


● Right now all these applications let’s say Course Service wants to connect to the

Address Service, Student Service wants to connect to the Course Service, and

wants to get some course-related data then how will these servers communicate

with each other?

● We will simply make a REST call and all these servers will communicate with

each other using the REST API.

● But the real challenging part is when a server wants to connect to another server

then before this server connects to this server it needs to know the IP address,

and it needs to know the port number where this particular application is running

in the server.
● Don’t you think managing the IP and the server URL will be critical?

● In the case of a Monolithic Application, there we have only one server so

we used to remember the server IP and the port but now your

monolithic has been split into thousands of applications how’ll be

handling that?

● And for that Spring Cloud is providing us with Service Discovery and

Service Registry to handle this problem.


What’s Service Discovery and Service Registry in
Microservices?
● Suppose we have Service-A & Service-B and we have our Load Balancer placed

inside a different server.

● Now let’s introduce our Discovery Service. Now what this discovery service will

do now whenever Service-A and Service-B want to communicate with each other

then whenever we are starting our Microservices we’ll be registering them with

Discovery Service.

● And this discovery service right now will know what is the IP and port number of

Service-A and what is the IP and port number of Service-B.


● All detailed information will be there with Discovery Service.

● Similarly, if we have many different instances of Service-B, all this Service-B

which is running in different servers will be registering their information with

Discovery Service.

● So it is one central location where we’ll be managing our host and the port

number information inside this particular server.

● This is basically called registration because all the services whenever they are

starting off they are registering themselves with the discovery service and now

the discovery service is maintaining all their information inside a particular map

or a list or a database. We called it a Service Registry.


● So, Service Registry is a crucial part of service identification.

● It’s a database containing the network locations of service instances.

● A Service Registry must be highly available and up-to-date.

● Here, inside Service Registry we have 4 different instances of Service-B

and they are running in some port number and some IP address.

● Similarly, for Service-A we have one different instance.


● Now Service-A wants to connect to Service-B.

● Now the load balancer once get the request, it is gonna do a query with the

discovery service that, hey, can you tell me what instances are there for Service-

B?

● Now the load balancer finds out that there are this many instances available

where Service-B has been deployed.

● Now Load Balancer is going to dispatch to one of the servers by looking into

Service Registry.

● It can take all four instances of Service-B and whoever has less load then to

balance the load, it can send the request to there.


● This is not going to be a simple job to manage the thing where you have

thousands and thousands of applications.

● How you will manage the server IP?

● How you’ll maintain their port number?

● Because every server, when you want some data from another server, it needs to

connect to them, and in order to connect to them it needs to know the IP and the

server address of that and it will be a really critical job to handle all the IP and the

server ports where you have thousands of servers where you have split your one

application into thousands of different modules and deployed into different

servers
Types of Service Discovery

● There are two types of Service Discovery

○ Client-Side Service Discovery

○ Server-Side Service Discovery

● Point to Remember:

○ Client-Side Service Discovery Example: Netflix Eureka, Zookeeper, Consul

○ Server-Side Service Discovery Example: NGNIX, AWS ELB


Eureka
● Introduction to Eureka Server:

○ Eureka Server is a key component of the Netflix OSS stack and is widely used

in microservices architectures for service discovery.

○ In a microservices environment, different services need to communicate with

each other, and Eureka Server helps manage this communication efficiently.

○ Eureka Server is a Service Registry that holds information about all the

running services and their locations.


● Key Features of Eureka Server:

○ Service Registration: When a microservice starts, it registers itself with the

Eureka Server by sending its metadata (like IP address, port, and service name).

○ Service Discovery: When a microservice needs to communicate with another,

it asks Eureka Server for the address of the required service.

○ Heartbeat Mechanism: Registered services send periodic heartbeats to the

Eureka Server to inform it that they are still available. If the heartbeat stops, the

Eureka Server assumes that the service is down and removes it from the registry.
● How Eureka Server Works:

○ Setting up Eureka Server: You create a Eureka Server application that

acts as the Service Registry. This server will hold all the information about

the services.

○ Service Registration: Each microservice will be configured as a Eureka

Client. When the microservice starts, it registers itself with the Eureka

Server. This allows the Eureka Server to know the address of each service.
● Service Discovery: When one microservice (say Service A) needs to

communicate with another (Service B), it will ask the Eureka Server for

the location of Service B. Eureka Server responds with the necessary

details, and Service A can then connect to Service B.

● Fault Tolerance: If a service goes down, Eureka detects this through the

heartbeat mechanism and removes the service from its registry, ensuring

other services don’t attempt to connect to a non-functional service.


● Eureka Server in Microservices Architecture:

○ Eureka Server is essential for dynamic scaling in cloud environments.

○ For instance, if you deploy multiple instances of a service for load

balancing, Eureka Server helps manage these multiple instances.

○ When a new instance of a service is created, it automatically registers

with Eureka, and when an instance is removed or fails, Eureka deregisters

it.
● Why Use Eureka?

○ Scalability: Eureka supports multiple instances of services and

automatically manages them.

○ Fault Tolerance: Eureka allows microservices to be resilient by rerouting

traffic to healthy services when one fails.

○ Dynamic Registration: No need to hard-code service addresses;

services register and update automatically.


● Example:

○ Imagine an online shopping platform with multiple microservices like User

Service, Inventory Service, and Order Service.

○ Each service is deployed independently.

○ When the Order Service needs to check item availability in the Inventory

Service, it asks Eureka Server for the location of the Inventory Service,

gets the address, and communicates directly.


Consul
● Introduction to Consul:

○ Consul is a widely used tool for service discovery and configuration

management in microservices architectures.

○ It provides a distributed, highly available system for service registration,

health checks, and key-value storage.


● Key Features of Consul:

○ Service Discovery: Microservices register themselves with Consul, and

other services can discover them dynamically.

○ Health Checks: Consul constantly checks the health of registered

services. If a service fails, it is automatically deregistered.

○ Key-Value Store: Consul includes a key-value store that can be used for

configuration management across microservices.

○ DNS and HTTP Interfaces: Consul supports both DNS and HTTP APIs for

querying the service registry.


● How Consul Works:

○ Service Registration: Microservices register with Consul, providing

metadata such as IP address and port.

○ Service Discovery: Other microservices query Consul to find available

services using either DNS or HTTP requests.

○ Health Monitoring: Consul monitors the health of services and removes

any failed services from the registry.


● Why Use Consul?

○ Built-in Health Checks to ensure services are available.

○ Configuration Management for dynamic, distributed systems.

○ Multi-datacenter Support for global scaling.


Zookeeper
● Introduction to Zookeeper:

○ Zookeeper is an Apache project primarily used for distributed

coordination.

○ It is widely adopted for service discovery, configuration management, and

leader election in microservices environments.


● How Zookeeper Works:

○ Service Registration: Microservices register their details (such as IP and

port) with Zookeeper.

○ Service Discovery: Other microservices query Zookeeper to find the

location of registered services.

○ Leader Election: Zookeeper helps select a leader in cases where

coordination is required among microservices.


● Why Use Zookeeper?

○ Leader Election for distributed systems.

○ Reliable Configuration Storage in dynamic environments.

○ Scalable for large, distributed microservices architectures.


API Gateway Functionality
● In a microservices architecture, an API Gateway acts as a crucial intermediary

layer that sits between clients (users) and the various microservices.

● Its primary job is to handle requests from the clients and route them to the

appropriate microservices.

● It serves as the single entry point for all client requests, playing an essential

role in managing communication between clients and microservices.

● Key Roles of an API Gateway:


○ Routing
○ Composition
○ Protocol Translation
Routing
● Routing is one of the primary responsibilities of an API Gateway in microservices.

● It involves directing incoming requests to the correct microservice based on the

request path, HTTP method, or other criteria.

● How it works:

○ When a client sends a request to the API Gateway, the gateway examines

the request and determines which microservice should handle it.

○ For instance, a request for customer data (/customers) would be routed to

the Customer Service, while a request for orders (/orders) would be routed

to the Order Service.


● Advantages:

○ Centralized control: The API Gateway acts as a single point of contact

for all services, which simplifies routing logic and makes it easier to

manage.

○ Dynamic routing: The gateway can route requests dynamically based

on factors such as traffic load, service availability, or user-specific

requirements.

○ Flexible request distribution: The API Gateway can apply load-

balancing strategies by distributing requests among multiple instances of


● Example:

○ Suppose you have three microservices: User Service, Product Service, and

Order Service.

○ The API Gateway routes the /users path to the User Service, /products to

the Product Service, and /orders to the Order Service.

○ Clients only need to know the single API Gateway endpoint instead of

multiple service addresses.


Composition
● In microservices architectures, there are often cases where a single client request

may require data or operations from multiple microservices.

● Composition refers to the ability of the API Gateway to aggregate or compose

responses from multiple microservices into a single response.

● How it works:

○ When a client requests data that spans several microservices, the API

Gateway can act as an orchestrator.

○ Instead of the client making multiple calls to different services, the API

Gateway makes the necessary service calls, gathers the results, and returns

a unified response to the client.


● Advantages:

○ Reduced round-trip time: Instead of making multiple network requests

to different services, the client receives all necessary data in a single

response, reducing the time and overhead.

○ Simplified client interactions: Clients do not need to know how to

interact with individual microservices. The API Gateway handles all the

complexity behind the scenes.

○ Aggregation of data: The gateway can combine responses from different

microservices into a single response that fits the client’s requirements.


● Example:

○ Suppose a client requests the details of an order, including customer

information and product details.

○ The Order Service may store only the order data, so the API Gateway

needs to fetch customer details from the Customer Service and product

information from the Product Service.

○ The API Gateway composes a complete response by aggregating the

outputs of the three services.


Protocol Translation
● Microservices can communicate using different protocols, such as HTTP,

WebSocket, gRPC, or messaging protocols like AMQP.

● Protocol translation is the process by which an API Gateway translates one protocol

into another, enabling services to interact seamlessly even if they use different

communication methods.

● How it works:

○ The API Gateway receives a request using one protocol (e.g., HTTP) and

translates it into the protocol used by the target microservice (e.g., gRPC).

○ After receiving the response from the service, the API Gateway converts it

back to the original protocol format before sending it to the client.


● Advantages:

○ Compatibility: The gateway allows clients using standard protocols like

HTTP to interact with services using more optimized protocols like gRPC.

○ Protocol abstraction: Clients do not need to worry about the specific

communication protocols used by each microservice. The API Gateway

abstracts the underlying complexity, allowing clients to use a unified

interface.

○ Support for legacy systems: API Gateways can help integrate

microservices with legacy systems that might use outdated communication

protocols.
● Example:

● Imagine that your front-end application communicates over HTTP/REST, but

one of the microservices uses gRPC for optimized communication.

● The API Gateway will handle the conversion from HTTP to gRPC and back,

allowing both the client and microservice to communicate without being aware

of each other’s protocols.


Additional Functionalities
● Security:

○ API Gateways often handle authentication (e.g., OAuth, JWT) and

authorization to ensure only authorized users can access certain services.

● Rate Limiting and Throttling:

○ They can enforce rate limits to prevent clients from overwhelming the

services with too many requests.

● Caching:

○ API Gateways can cache responses from services to improve performance and

reduce load on microservices.


● Logging and Monitoring:

○ They provide logging, metrics, and tracing capabilities to help monitor

service usage and performance.

● Fault Tolerance and Circuit Breaking:

○ API Gateways can implement circuit breakers, retry mechanisms, and

timeouts to ensure that failures in downstream services do not

propagate to the clients.

You might also like