Spring Cloud
Spring Cloud
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.
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.
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 {
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.
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
Microservices : -
Advantages of Microservices
Scalability
Modularity
Micro-service ( more generic problems )
monolitic application( specific to my program and secnario )
@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)
Webclient :- its asynchronous, we can call web client with the help of builder
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.
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 don’t need to fetch the registry and register itself to registry
because it is server which handle all registry
Dependency
```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();
}
}
```
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class MyService {
@Autowired
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
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
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,
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)
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
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
@value (“${my.greeting}”)
@value (“hello world”)
@value (“${my.greeting: default value }”)
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?
```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'
}
```
```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.
```properties
server.port=8080
```
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.