Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Spring Cloud

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 27
At a glance
Powered by AI
The key takeaways are that microservices architecture breaks down monolithic applications into smaller, independent services where each service handles a specific business goal/feature. This makes microservices easier to develop, deploy and scale compared to monolithic architecture.

Some advantages of microservices architecture over monolithic architecture are that microservices have easier fault isolation, quicker service startup, loose coupling between services and consistent availability of each microservice.

The different types of filters in Netflix Zuul API gateway are pre filters, post filters, route filters and error filters. Pre filters are invoked before request routing, post filters after, route filters for routing requests, and error filters on errors.

Spring Cloud

Anuj Tripathi
Microservices Monolithic Architecture
Every unit of the entire application should be the A single code base for all business goals
smallest, and it should be able to deliver one specific
business goal.

Service Startup is relatively quick Service startup takes more time


Fault isolation is easy. Even if one service goes down, Fault isolation is difficult. If any specific feature is not
other can continue to function. working, the complete system goes down. In order to
handle this issue, the application needs to re-built, re-
tested and also re-deployed.

All microservices should be loosely coupled so that Monolithic architecture is tightly coupled. Changes in
changes made in one does not affect the other. one module of code affect the other

Microservices always remains consistent and Development tools get overburdened as the process
continuously available. needs to start from the scratch.

Development tools get overburdened as the process Data is centralized.


needs to start from the scratch.

Change in the data model of one Microservice does Change in data model affects the entire database
not affect other Microservices.
Configuration- Config Server
Config server is where all configurable parameters of microservices are written and maintained. It is more
like externalizing properties / resource file out of project codebase to an external service altogether, so that
any changes to that property does not necessitate the deployment of service which is using the property. All
such property changes will be reflected without redeploying the microservice

Configuration - Client Side


Now we will proceed to the client side implementation where we will use those properties from a separate
microservice which is our final goal – to externalize the configuration to different service.

Service Discovery - Netflix Eureka


We will be using Spring Boot based Spring Cloud API. We will use Netflix Eureka server for building the
service registry server and Eureka clients which will register themselves and discover other services to call
REST APIs
Circuit breaker - Hystrix Circuit Breaker

circuit breaker while invoking underlying microservice. It is generally required to enable fault tolerance in the
application where some underlying service is down/throwing error permanently, we need to fall back to
different path of program execution automatically

Api Gateway-Netflix zuul api gateway


create load balancer using Netflix Zuul and its solid bonding with Spring Cloud. Here we will mainly
concentrate on API gateway pattern and it’s usage. We will build a netflix zuul where we will create a
microservice ecosystem and test its effectiveness and applicability of Zuul API gatewayin the whole
ecosystem
Tracing - Zipkin and Sleuth
Zipkin is very efficient tool for distributed tracing in microservices ecosystem. Distributed tracing, in
general, is latency measurement of each component in a distributed transaction where multiple
microservices are invoked to serve a single business usecase. Let’s say from our application, we have to call
4 different services/components for a transaction. Here with distributed tracing enabled, we can measure
which component took how much time.
Spring Cloud Pipelines
Spring, Spring Boot and Spring Cloud are tools that allow developers speed up the time of
creating new business features. It’s common knowledge however that the feature is only valuable
if it’s in production. That’s why companies spend a lot of time and resources on building their own
deployment pipelines.
This project tries to solve the following problems:

• Creation of a common deployment pipeline


• Propagation of good testing & deployment practices
• Speed up the time required to deploy a feature to production
A common way of running, configuring and deploying applications lowers support costs and time
needed by new developers to blend in when they change projects.

Currently, we support the following CI / CD systems out of the box


• Concourse
• Jenkins
• Eureka Service Registry Server – This microservice will provide the service registry and discovery
server.
• Student Microservice – Which will give some functionality based on Student entity. It will be a rest
based service and most importantly it will be a eureka client service, which will talk with eureka service
to register itself in the service registry.
• School Microservice – Same type as of Student service – only added feature is that it will invoke
Student service with service look up mechanism. We will not use absolute URL of student service to
interact with that service.
Here is the interaction diagram between above listed three services.

Component Interaction with each other Eureka Service Registry Server


Follow these steps to create and run Eureka server.

Create Eureka Server

Create a Spring boot project from Spring Boot initializer portal with two dependencies i.e. Eureka server
and Actuator. Give other maven GAV coordinates and download the project.

Eureka Server Service Project Generation


Unzip and import the project into Eclipse as existing maven project. In this step, all necessary
dependencies will be downloaded from maven repository.

Now open SpringEurekaServerApplication class that spring already has generated in the
downloaded project and add the @EnableEurekaServerannotation on the class.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class SpringEurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringEurekaServerApplication.class, args);
}
}
Build the project once again. With this annotation, this artifact will act like microservice registry
and discovery server.
Server Configuration

Create one file called application.yml in the src\main\resources directory. Add these properties

server:
port: ${PORT:8761} # Indicate the default PORT where this service will be started
eureka:
client:
registerWithEureka: false #telling the server not to register himself in the service registry
fetchRegistry: false
server:
waitTimeInMsWhenSyncEmpty: 0 #wait time for subsequent sync
Create another file called bootstrap.yml in the src\main\resources directory. Add these
properties –

spring:
application:
name: eureka
cloud:
config:
uri: ${CONFIG_SERVER_URL:http://localhost:8888}
Start the application as spring boot application. Open browser and go to
http://localhost:8761/, you should see the eureka server home page which looks like below.
Create Eureka Client Project
Now add the @EnableEurekaClient annotation on Spring boot application class present in src
folder. With this annotation, this artifact will act like a spring discovery client and will register
itself in the eureka server attached to this service.

import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class SpringEurekaClientStudentServiceApplication {
public static void main(String[] args) {
SpringApplication.run(SpringEurekaClientStudentServiceApplication.class, args);
}
}
Client Configuration

Create one file called application.yml in the src\main\resources directory and add below lines.
server:
port: 8098 #default port where the service will be started

eureka: #tells about the Eureka server details and its refresh time
instance:
leaseRenewalIntervalInSeconds: 1
leaseExpirationDurationInSeconds: 2
client:
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
healthcheck:
enabled: true
lease:
duration: 5
spring:
application:
name: student-service #current service name to be used by the eureka server
Add REST API
Now add one RestController and expose one rest endpoint for getting all the student details for a
particular school. Here we are exposing /getStudentDetailsForSchool/{schoolname} endpoint to
serve the business purpose. For simplicity, we are hard coding the student details.

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

@RestController
public class StudentServiceController {
private static Map<String, List<Student>> schooDB = new HashMap<String, List<Student>>();
static {
schooDB = new HashMap<String, List<Student>>();
List<Student> lst = new ArrayList<Student>();
Student std = new Student("Sajal", "Class IV");
lst.add(std);
schooDB.put("xyzschool", lst);
}
@RequestMapping(value = "/getStudentDetailsForSchool/{schoolname}", method =
RequestMethod.GET)
public List<Student> getStudents(@PathVariable String schoolname) {
System.out.println("Getting Student details for " + schoolname);
List<Student> studentList = schooDB.get(schoolname);
if (studentList == null) {
studentList = new ArrayList<Student>();
Student std = new Student("Not Found", "N/A");
studentList.add(std);
}
return studentList;
}
We will now verify that the /getStudentDetailsForSchool/{schoolname} endpoint is up and running. Go to browser and go to
http://localhost:8098/getStudentDetailsForSchool/abcschool, it will give the Student details for a particular school abcschool.
Hystrix Circuit Breaker
1. Add Hystrix starter and dashboard dependencies.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>

2. Add @EnableCircuitBreaker annotation


3. Add @EnableHystrixDashboard annotation
4. Add annotation @HystrixCommand(fallbackMethod = "myFallbackMethod")
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@Service
public class StudentServiceDelegate {

@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "callStudentServiceAndGetData_Fallback")

public String callStudentServiceAndGetData(String schoolname) {


System.out.println("Getting School details for " + schoolname);
String response = restTemplate
.exchange("http://localhost:8098/getStudentDetailsForSchool/{schoolname}"
, HttpMethod.GET
, null
, new ParameterizedTypeReference<String>() {
}, schoolname).getBody();

System.out.println("Response Received as " + response + " - " + new Date());

return "NORMAL FLOW !!! - School Name - " + schoolname + " ::: " +
" Student Details " + response + " - " + new Date();
}
@SuppressWarnings("unused")

private String callStudentServiceAndGetData_Fallback(String schoolname) {


System.out.println("Student Service is down!!! fallback route enabled...");
return "CIRCUIT BREAKER ENABLED!!! No Response From Student Service at this moment. " +
" Service will be back shortly - " + new Date();
}

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Netflix zuul api gateway-Zuul Components
Zuul has mainly four types of filters that enable us to intercept the traffic in different timeline of the
request processing for any particular transaction. We can add any number of filters for a particular url
pattern.
• pre filters – are invoked before the request is routed.
• post filters – are invoked after the request has been routed.
• route filters – are used to route the request.
• error filters – are invoked when an error occurs while handling the request.

@SpringBootApplication
@EnableZuulProxy
public class SpringBootZuulgatwayproxyApplication {

public static void main(String[] args) {


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

book/src/main/resources/application.properties

spring.application.name=book
server.port=8090
To forward requests from the Gateway application, we need to @SpringBootApplication
tell Zuul the routes that @EnableZuulProxy
it should watch and the services to which to forward requests
public class SpringBootZuulgatwayproxyApplication {
to those routes. We specify routes using properties under
zuul.routes. public static void main(String[] args) {
SpringApplication.run(SpringBootZuulgatwayproxyApplication.class,
Each of our microservices can have an entry under args);
zuul.routes.NAME, where NAME is the application name (as }
@Bean
stored in the spring.application.name property).
public PreFilter preFilter() {
return new PreFilter();
}
@Bean
Add the application.properties file to a new directory, public PostFilter postFilter() {
src/main/resources, in the Gateway application. It should look return new PostFilter();
like this: }
@Bean
gateway/src/main/resources/application.properties public ErrorFilter errorFilter() {
return new ErrorFilter();
}
zuul.routes.books.url=http://localhost:8090 @Bean
public RouteFilter routeFilter() {
ribbon.eureka.enabled=false return new RouteFilter();
}
server.port=8080 }

Spring Cloud Zuul will automatically set the path to the


application name. In this sample because we set
zuul.routes.books.url, so Zuul will proxy requests to /books to
this URL.
Zipkin and Sleuth - Integration

lets create 4 spring boot based microservices. They all will have both Zipkin and Sleuth starter
dependencies. In each microservice, we will expose one endpoint and from the first service we will call
second service, and from second service we will invoke third and so on using rest Template.

And as we have already mentioned, Sleuth works automatically with rest template so it would send this
instrumented service call information to attached Zipkin server. Zipkin will then start the book keeping of
latency calculation along with few other statistics like service call details.

@GetMapping(value="/zipkin")
public String zipkinService1()
{LOG.info("Inside zipkinService 1..");
String response = (String) restTemplate.exchange("http://localhost:8082/zipkin2",
HttpMethod.GET, null, new ParameterizedTypeReference<String>() {}).getBody();
return "Hi...";
}
App Configurations

As all services will run in a single machine, so we need to run them in different ports. Also to
identify in Zipkin, we need to give proper names. So configure application name and port
information in application.properties file under resources folder.

server.port = 8081
spring.application.name = zipkin-server1

Similarly for other 3 services, we will use ports 8082, 8083, 8084 and name will also be like

zipkin-server2, zipkin-server3 and zipkin-server4.


Thanks

You might also like