0% found this document useful (0 votes)
26 views

Spring Cloud

springs

Uploaded by

HellHackers
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Spring Cloud

springs

Uploaded by

HellHackers
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Spring Cloud

WHY WE NEED SPRING CLOUD?


API Gateway and Eureka Server are both components commonly used in
microservices architectures, but they serve different purposes and play distinct
roles. Let's explore the difference between them:

1. API Gateway:
An API Gateway is a centralized entry point for clients to access various
microservices in a system. It acts as a reverse proxy that receives incoming
requests from clients and then routes them to the appropriate microservices
based on the request's endpoint or content. The API Gateway can also provide
additional functionalities such as authentication, authorization, load balancing,
caching, request/response transformation, and logging.

Key features of an API Gateway:


- Routing: Determines which microservice should handle a specific API request
based on the request's endpoint.
- Load Balancing: Distributes incoming requests across multiple instances of a
microservice to ensure optimal resource utilization and performance.
- Authentication and Authorization: Handles user authentication and authorization,
ensuring that only authorized clients can access specific services.
- Request/Response Transformation: May modify the request/response data to
match the expectations of the client or microservices.
- Logging and Monitoring: Collects and analyzes data on incoming requests and
system performance.

Popular API Gateway implementations include Kong, Apigee, AWS API Gateway,
and Nginx with additional plugins.

2. Eureka Server:
Eureka Server is a service registry and discovery server. In a microservices
architecture, services are often distributed across multiple instances and
locations. Eureka provides a way for microservices to register themselves with the
Eureka server and discover other services registered with it. This registration and
discovery mechanism enable microservices to find and communicate with each
other without hardcoding the URLs or IP addresses of the services they want to
use.

Key features of Eureka Server:


- Service Registration: Microservices register themselves with the Eureka server,
providing metadata about their location, health status, and other relevant
information.
- Service Discovery: Microservices query the Eureka server to find the locations of
other services they depend on. This enables dynamic load balancing and failover
between service instances.
- Heartbeat Monitoring: Eureka regularly checks the health status of registered
services, allowing it to remove instances that are unresponsive or unhealthy.

Eureka Server is part of the Netflix OSS (Open Source Software) suite and was
widely used with Spring Cloud for Java-based microservices. However, it's
essential to note that Netflix has now entered maintenance mode, and some
organizations may use alternative service registries like Consul or etcd.

In summary, while both API Gateway and Eureka Server are essential components
in microservices architectures, an API Gateway is responsible for managing the
entry point and providing additional functionalities for API requests, while Eureka
Server handles service registration and discovery to facilitate communication
between microservices.

Problems:
Spring cloud Open feign :-

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

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

@SpringBootApplication
@EnableFeignClients
public class ExampleApplication {

public static void main(String[] args) {


SpringApplication.run(ExampleApplication.class, args);
}
}

@FeignClient(value = "jplaceholder", url = "https://


jsonplaceholder.typicode.com/")
public interface JSONPlaceHolderClient {

@RequestMapping(method = RequestMethod.GET, value = "/posts")


List<Post> getPosts();

@RequestMapping(method = RequestMethod.GET, value = "/posts/{postId}",


produces = "application/json")
Post getPostById(@PathVariable("postId") Long postId);
}

In this example, we've configured a client to read from the JSONPlaceholder APIs.
The value argument passed in the @FeignClient annotation is a mandatory,
arbitrary client name, while with the url argument, we specify the API base URL.
Furthermore, since this interface is a Feign client, we can use the Spring Web
annotations to declare the APIs that we want to reach out to.

Spring Cloud Netflix Eureka: - we can have number of Microservices , if


we change the url of micro service , we need to change the url IT to all
the micro services , Here Eureka is introduced , service discover and
registry , each micro service is register with the eureka , each has its
unique id and name , our micro-service will communicate with other
Microservices with the help of service name not depend upon the url of
the service

Eureka properties :-
eureka.client.service-url.defaultZone=http://localhost:8761/eureka
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
spring.application.name=apiGateway

spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lower-case-service-id=true

Spring cloud load balancer :


Spring cloud API Gateway : any request come to Microservices will, first
hit the API gateWay and we can perform the common operation like:
Authentication, header populate and other tasks s well
Fault Tolerance: if my service is down , it will not effect the other
micro-service , here the concept of fault tolerance is introduced
(cuircuit breaker with resilient4j )
Sleuth and zipkin : - for logging purpose from one to another service
(zipkin 9411)
Config Server :- for the common properties between Microservices
(git repository)
Medium web page has documentation (regarding load balancer )

Microservices : -

Create a few micro-services


Having them communication with each other( we can hardcode and bind one
Microservices to other / we can discover the way through which we can register
the service and call each other which is more dynamic )

Advantages of Microservices
Scalability
Modularity
Micro-service ( more generic problems )
monolitic application( specific to my program and secnario )

Managing the complexity

– pattern :- Make the Microservices work well together


– Technologies : - its library and framework to solve common problems

How to run the application , with tomcat throughout command line?

Calling one services to another by using the REST APIs programatically


Using a REST client
RESTTemplate is a utility object which helps to communicate , rest template has
some methods

RestTemplate.getForObject(“url”, “provide the class which has the same properties


of the JSON payload”) :- this will help us marshalling and un-marshalling y rest
template by itself , by default it will return the string

REst template is the thread safe )

Eager and lazy initilization in bean creating?

@Autowire ( consumer , hi spring give the bean of the specific class )vs @bean
( producer ,I just created the class and it may be required type to consumer , save
it for future)

If awe are using the multiple rest template then we need to use the qualifier
( which is tag to let the spring know about which bean need to inject in the variable
while autowire)

Another way to call a microservices

Webclient :- its asynchronous, we can call web client with the help of builder

We are hardcoding the micro services url so , we need it to be dynamic


These are reason why we need to service discovery
We build Microservices , want to talk to each other , how they know whom to talk
to ,, they discover the target.
What is the minimal step we need for discovery server?
Provide the layer of abstraction
The above one is client side server discovery

And another one is server side server discovery which will remove the extra hops ,
we need to call discovery server and that will pass the method to the service and
return the response , this patterns is more effecient.

Spring cloud use the technology is eureka (Netflix css)

Eureka
Ribbon
Hysterix
Zulu

Spring will provide the absraction layer which will helps to communicate the all
above the service by spring.
Eureka client serve 2 things : - tell the eureka server I am available for other client
( publish )
:- request the eureka server for the data from other
client (consume)

Eureka server is not something that we need to download, its application

@enableEurekaServer is used on the main class

Eureka server don’t need to fetch the registry and register itself to registry
because it is server which handle all registry

PORT : 8761 for Eureka server

Dependency

Eureka service for eureka server


Eureka discovery for eureka client
@loadbalanced?

In Spring Cloud Eureka, the `@LoadBalanced` annotation is used in conjunction


with Spring's RestTemplate to enable client-side load balancing. Spring Cloud
Eureka is a part of the Spring Cloud suite of tools that provides support for
building microservices-based applications.

When you use the `@LoadBalanced` annotation on a RestTemplate bean, it


enables the integration with Spring Cloud's load balancing features. This means
that when you make HTTP requests using the RestTemplate, Spring Cloud Eureka
will automatically resolve the service instances' addresses registered with Eureka
and perform client-side load balancing among them.

Here's how you can use the `@LoadBalanced` annotation:

1. First, include the `spring-cloud-starter-netflix-eureka-client` dependency in


your project to enable Eureka client functionality.

2. Create a RestTemplate bean in your configuration class:

```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class MyConfiguration {

@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
```

3. Inject the `RestTemplate` bean into your service or controller:

```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class MyService {

private final RestTemplate restTemplate;

@Autowired
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}

public void doSomething() {


// Use the restTemplate to make HTTP requests
String response = restTemplate.getForObject("http://my-service/api/
resource", String.class);
// ...
}
}
```

In the example above, when you use `restTemplate.getForObject(...)`, Spring


Cloud Eureka will automatically resolve the service name (`my-service` in this
case) to the available instances registered in the Eureka server and apply client-
side load balancing among them.

By using the `@LoadBalanced` annotation with RestTemplate, you can take


advantage of Eureka's service discovery and load balancing capabilities to interact
with other microservices in your environment more efficiently and reliably.

If eureka server down for some time , what will happened?


Then cache will take place on the side of the client ( all are manage by eureka
server client
Will check its own cache(Client) and work on it.
Fault tolerance :- given the application , if there is fault what is the impact if that
fault and how much tolerance application does the system have specific fault ,
If the one Microservices is go down, what happen to ur Microservices , is ti whole
Microservices go down or part of the Microservices go down or there are some
way to handle the failure of Microservices.

Fault tolerance :-What tolerance your system has for the particular fault is
known as the fault tolerance.

Resilience :- how many fault a system tolerate before it broke down, how
much system can bounce back from the fault , if something goes down

If Microservices is down :- then create another instance


If Microservices is slow :- then time out process

How can we set the timeouts on spring restTemplate

Add the property to the class which is passed by the restTemplate while creating
bean. But there is one issue in this , it will partially solve the problem
If the request coming is too fast and timeout is bit high , it will not leave the thread
till the timeout is not over, in that scenario we will use the circuit breaker.
Its a precaution which is taken, will detach, if the service is slow , it will not send
request till it will come to its original speed.
This is how the circuit breaker works.

If the one microservice is calling 2 Microservices on one call , there must be circuit
implement in that application,

Difference between eureka server and API Gateway?

Circuit breaker properties


How many request we need to check , it’s tricky .

Now everything is good with circuit break , then what to do with the request :-
– Throw an error (not recommended)
– Return a fallback “default” response ( recommend)
– Save the previous response(cache) and use that when possible. (Best
approach)

Why circuit breakers?


– Failing fast - it is good thing, its better to fail early rather than take time
and fail later.
– Fall back functionality
– Automatic recovery

Circuit braker pattern


– When to break circuit ?
– What to do when the circuit breaks
– When to resume the request

Now everything is good with circuit break , then what to do with the request :-
– Return a fallback “default” response ( recommend)—> For this, Hystrix

technology is used
– Hystrix: - open source library created by Netflix
– Implements circuit breaker pattern so you don’t have to
– Give the configuration params and it does the work
– Works well with spring-boot

How to implement Hystrix

– Add dependency spring-cloud-starter-netflix-hystrix


– Add @EnableCircuitBreaker to application class
– Add @HystrixCommand to the method where we need to break the circuit
– Configure the Hystrix behaviour
– @HystrixCommand(fallback = “method Name”) - > it will contain value
form cache or hardcode value

What is the problem of the Hystrix implementation?


When we write the hysteric method in the same class where the method or
mapping is implemented , then Hysteric annotation is not working,
As per Hystrix rules ,it always work with the instance calling outside, not for the
same class ( same class instance )
Properties that break the circuit

Want to check the last 5 value then —> requestVolumeThreshold


unsucessfull request percentage ⸻> errorVolumeThreshold
sleepWindowInMilliseconds ⸻> again connect the trip of circuitBreaker.

HystrixDashboard
This is the url
/hystrix
And url:- /actuator/hystrix.stream
What is Microservices configuration and why we need configuration?

Don’t Hardcode these thing in code define the value in the properties or yaml file
or json -
Like - Database connection
– Credentials
– Feature flags
– Business logic Configuration parameters
– Scenario testing
– springBoot configuration

Configuration Goals
– Externalized
– Environment specific
– Consistent
– Version history
– Real time management

3 ways to use Value

@value (“${my.greeting}”)
@value (“hello world”)
@value (“${my.greeting: default value }”)

@ConfigurationProperties(“prefix”) : it does not create bean , we need to add


@configuration to create a bean

Spring Cloud Config Server

Externalized : - (properties files)


eviornment Specific : profile

Consistent , version history is not achieved yet


Version control is done by the Git repo
:- implementation of the Config Server
– Add dependency ( tell us from where we can fetch the data - git, SVN,
hasicorp )
– @EnableConfigServer on application class
– Add properties spring.cloud. config.server.git.url= “address of the url”

Here hone is the system variable
File name is = application.yml (only name no extension )
What Is the url : - http://localhost:8888(it should be anything)/file-
name(application)/profile-name(default)

– spring- cloud- starter -config add dependency


– Add version in the management
– Add properties :- spring.cloud.config.uri = http://localhost:8080/

Want to add the number of properties file and use it by adding the
spring.application.name
@RefreshScope will help to update the value
WHAT IS API GATEWAY AND ITS IMPLEMENTATION?

In a microservices architecture, an API Gateway is a critical component that acts


as the single entry point for clients to access various microservices. It provides a
unified interface, performs request routing, and offers additional functionalities
such as authentication, authorization, load balancing, caching, and logging. In
Spring Boot, you can implement an API Gateway using Spring Cloud Gateway,
which is part of the Spring Cloud ecosystem.

Below is a step-by-step guide to implementing an API Gateway using Spring Boot


and Spring Cloud Gateway:

Step 1: Set up a new Spring Boot Project


Create a new Spring Boot project using your preferred IDE or the Spring Initializr
(https://start.spring.io/). Include the following dependencies in your `pom.xml` or
`build.gradle` file:
For Maven:

```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
```

For Gradle:

```groovy
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
}
```

Step 2: Configure the API Gateway


Create a configuration class for your API Gateway. This class will define the routing
rules and any additional filters you want to apply. Filters can handle cross-cutting
concerns like authentication and logging.

```java
@Configuration
public class GatewayConfig {

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("example_route", r -> r.path("/example")
.uri("http://example-service")) // Replace "example-service" with
the actual service URL
.route("another_route", r -> r.path("/another")
.uri("http://another-service")) // Replace "another-service" with the
actual service URL
.build();
}
}
```

In this example, we've created two simple routes to route requests with specific
paths to different backend services.

Step 3: Configure application properties


In your `application.properties` or `application.yml`, you can configure the port
and any other necessary properties.

```properties
server.port=8080
```

Step 4: Run the API Gateway


Run your Spring Boot application. The API Gateway will be available at `http://
localhost:8080`.

Step 5: Access the Microservices through the API Gateway


Now, you can access your microservices through the API Gateway using the
defined routes. For example, if you have a service running at `http://example-
service/example`, you can access it through the API Gateway at `http://
localhost:8080/example`.

This is a basic setup of an API Gateway using Spring Cloud Gateway. Depending
on your requirements, you can add more advanced features, such as request/
response transformation, load balancing, and security filters, to suit your specific
use case. Spring Cloud Gateway provides a flexible and powerful framework for
building robust API Gateways in a Spring Boot microservices environment.

Default port of zipkin:- 9411

How zipkin and slueth is working together ?


Why TraceId and Spam Id is same in any scenario?
When we do zipkin enabled false ?

You might also like