# Why do I need to learn Spring Cloud
Whether it’s a business application or a user application, it’s very simple at the beginning of the business, and we usually implement it as a monolithic application. However, as the business evolves, product ideas become more and more complex, and so does the application of single structures. This leads to the following problems for the application:
-
Chaotic code structure: Complex services lead to a large amount of code, which becomes increasingly difficult to manage. At the same time, it also poses a huge challenge to the rapid iteration of the business;
-
Less efficient development: Developers develop a set of code at the same time, and it is difficult to avoid code conflicts. The development process will be accompanied by constant conflict resolution process, which will seriously affect the development efficiency;
-
Troubleshooting costs are high: Online services find bugs and the process of fixing bugs may be simple. However, because there is only one set of code, it has to be recompiled, packaged, and put online, which is costly.
As the application of single structure increases with the increase of system complexity, various problems will be exposed. In recent years, microservice architectures have gradually replaced monolithic architectures, and this trend will become more and more popular. Spring Cloud is the most commonly used microservice development framework and has been widely used in enterprise development. Compiled a Java interview treasure book complete PDF
# What is Spring Cloud
Spring Cloud is an ordered collection of frameworks. It takes advantage of the development convenience of Spring Boot to subtly simplify the development of distributed system infrastructure, such as service discovery registry, configuration center, intelligent routing, message bus, load balancing, circuit breakers, data monitoring, etc., which can be started and deployed with one click with Spring Boot’s development style.
Instead of reinventing the wheel, Spring Cloud simply combines mature, proven service frameworks developed by various companies and encapsulates them in Spring Boot style, eliminating complex configuration and implementation principles. Finally, a simple and easy to understand, easy to deploy and easy to maintain distributed system development kit was set aside for developers.
# Design goals and strengths and weaknesses
Design goals
Coordinate microservices to simplify distributed system development.
The advantages and disadvantages
There are so many microservices frameworks such as Dubbo and Kubernetes, why use Spring Cloud?
Advantages:
-
Produced by the Spring family, Spring is unrivaled in the enterprise development framework, with a big head, which can guarantee the subsequent update and improvement
-
Rich components, complete functions. Spring Cloud provides very complete support for microservice architectures. For example, configuration management, service discovery, circuit breakers, microservice gateways, etc.
-
The Spring Cloud community is active, tutorials are plentiful, and it’s easy to find solutions to problems
-
The service separation granularity is finer and the coupling degree is lower, which is beneficial to resource reuse and improve development efficiency
-
We can make optimized service plans more accurately and improve the maintainability of the system
-
Reduce the cost of the team, you can develop in parallel, you don’t have to worry about other people’s development, you can focus on your own development first
-
Microservices can be cross-platform and can be developed in any language
-
Suitable for the Internet era, product iteration cycle is shorter
Disadvantages:
-
There are too many micro-services and high management costs, which are not conducive to system maintenance
-
The high cost of distributed system development (fault tolerance, distributed transactions, etc.) is a big challenge for the team
Generally speaking, the advantages of Spring Cloud outweigh the disadvantages. At present, Spring Cloud is a very complete set of distributed framework. At present, many enterprises start to use micro services, and the advantages of Spring Cloud are obvious. Therefore, learning Spring Cloud is a good choice for students who want to study microservices architecture.
# Spring Cloud development prospects
Spring Cloud is a boon for small and medium sized Internet companies, which often do not have the resources or financial resources to develop their own distributed system infrastructure. Using Spring Cloud’s one-stop solution can significantly reduce development costs while taking their business in stride.
At the same time, with the popularity of microservice architecture and Docker container concept in recent years, Spring Cloud will also have a neutral place in the future more and more “Cloud” software development style, especially in a variety of distributed solutions to provide standardized, full-site technology solutions. The significance may be comparable to the birth of the Servlet specification, effectively promoting the technological level of the server software system.
# Overall architecture
# Major projects
The sub-projects of Spring Cloud can be roughly divided into two categories. One is the encapsulation and abstraction of the existing mature framework “Spring Booting “, which is also the largest number of projects. The second type is the implementation of the infrastructure of a part of distributed system. For example, Spring Cloud Stream plays the role of Kafka and ActiveMQ.
Spring Cloud Config
The centralized configuration management tool is a unified external configuration management tool in distributed systems. By default, Git is used to store configuration, and it can support client configuration refresh, encryption, and decryption operations.
Spring Cloud Netflix
Netflix OSS open source component integration, including Eureka, Hystrix, Ribbon, Feign, Zuul and other core components.
-
Eureka: Service governance component, including server-side registry and client-side service discovery mechanism;
-
Ribbon: Load balancing service invocation component with multiple load balancing invocation strategies
-
Hystrix: Service fault tolerant component that implements circuit breaker mode and provides fault tolerance for service-dependent errors and delays;
-
Feign: Declarative service invocation components based on the Ribbon and Hystrix;
-
Zuul: API gateway component that provides routing and filtering for requests.
Spring Cloud Bus
A message bus for propagating cluster state changes, using lightweight message brokers to link nodes in a distributed system, can be used to dynamically refresh service configurations in a cluster.
Spring Cloud Consul
Service governance component based on Hashicorp Consul.
Spring Cloud Security
Security toolkit for load balancing OAuth2 client and login authentication in Zuul agent.
Spring Cloud Sleuth
Distributed request link tracing for Spring Cloud applications, with support for Zipkin, HTrace, and log-based tracing (such as ELK).
Spring Cloud Stream
A lightweight event-driven microservice framework that can send and receive messages using a simple declarative model, mainly implemented as Apache Kafka and RabbitMQ.
Spring Cloud Task
A microservice framework for quickly building ephemeral, limited data processing tasks to add functional and non-functional features to applications.
Spring Cloud Zookeeper
Service governance component based on Apache Zookeeper.
Spring Cloud Gateway
API gateway component that provides routing and filtering capabilities for requests.
Spring Cloud OpenFeign
A declarative service invocation component based on the Ribbon and Hystrix that dynamically creates interface implementations based on Spring MVC annotations for service invocation has replaced Feign as a first class citizen in Spring Cloud 2.0. Compiled a Java interview treasure book complete PDF
# Versioning of Spring Cloud
Spring Cloud is an integrated project made up of many sub-projects, each with a different release rhythm. In order to manage the version dependencies between Spring Cloud and each of the subprojects, a checklist has been published containing the subproject versions corresponding to a Spring Cloud version.
In order to avoid confusion between the Spring Cloud release number and the sub-project version number, Spring Cloud releases are named by name rather than version number. The names of these releases are the names of London Underground stations, and they correspond to the chronological order of releases in alphabetical order. For example, Angel is the first version, Brixton is the second version.
When Spring Cloud releases have reached a critical mass or a major BUG has been resolved, a “service Releases “version, or SRX, is released, For example, Greenwich.SR2 is the second SRX release of Greenwich released by Spring Cloud. The latest version of Spring Cloud is Hoxton.
Mapping between Spring Cloud and SpringBoot versions
The Spring Cloud corresponds to each sub-project version
Note: The Hoxton release is built on SpringBoot 2.2.x and does not apply to The 1.5.x release. With the cessation of maintenance for SpringBoot 1.5.x in August 2019, the Edgware version will also be discontinued.
What is the difference between SpringBoot and SpringCloud?
SpringBoot focuses on developing individual microservices quickly and easily.
SpringCloud is a global microservice coordination and management framework. It integrates and manages individual microservices developed by SpringBoot and provides integrated services such as configuration management, service discovery, circuit breaker, routing, micro proxy, event bus, global lock, decision campaign, distributed session, etc
SpringBoot can be independently used for development projects without SpringCloud, but SpringCloud is dependent on SpringBoot
SpringBoot focuses on developing individual microservices quickly and easily, while SpringCloud focuses on a global service governance framework.
# When developing distributed micro-services using Spring Boot, we face the following issues
(1) Complexity associated with distributed systems – this overhead includes network issues, latency costs, bandwidth issues, and security issues.
(2) Service discovery – The service discovery tool manages how processes and services in the cluster look up and talk to each other. It involves a catalog of services in which you can register services and then be able to find and connect to services in that catalog.
(3) redundancy – the redundancy problem in distributed system.
(4) Load balancing — Load balancing improves the distribution of workloads across multiple computing resources, such as computers, computer clusters, network links, central processing units, or disk drives.
(5) Performance – Issues Performance issues due to various operational overhead.
(6) Deployment complexity -Devops skill requirements.
What does # service registration and discovery mean? How is Spring Cloud implemented?
When we start a project, we usually do all the configuration in the properties file. As more services are developed and deployed, adding and modifying these properties becomes more complex. Some services may decline and some locations may change. Manually changing properties can cause problems.
Eureka service registration and discovery can help in this situation. Because all services are registered on the Eureka server and lookup is done by calling the Eureka server, there is no need to handle any changes and processing of the service location.
# Difference between Spring Cloud and Dubbo?
Dubbo is RPC SpringCloud Rest Api
(2) Registry, Dubbo is ZooKeeper, SpringCloud is Eureka, and it can also be ZooKeeper
(3) Service gateway,dubbo itself is not implemented, can only be integrated through other third-party technologies, SpringCloud has Zuul routing gateway, as a routing server, for consumer request distribution, SpringCloud supports circuit breakers, perfect integration with Git configuration file support version control, The transaction bus implements a series of microservice architecture elements such as configuration file update and automatic service assembly.
What is the significance of load balancing?
In computing, load balancing can improve workload distribution across multiple computing resources such as computers, computer clusters, network links, central processing units, or disk drives. Load balancing is designed to optimize resource usage, maximize throughput, minimize response time, and avoid overloading any single resource. Load balancing with multiple components rather than a single component may improve reliability and availability through redundancy. Load balancing typically involves proprietary software or hardware, such as multi-tier switches or domain name system server processes.
# What is Hystrix? How does it achieve fault tolerance?
Hystrix is a delay and fault tolerant library designed to isolate access points to remote systems, services and third party libraries, stopping cascading failures when failures are unavoidable and enabling resilience in complex distributed systems.
Typically for systems developed using a microservice architecture, many microservices are involved. These microservices work with each other.
Consider the following microservices
Suppose that if microservice 9 in the figure above fails, we will propagate an exception using traditional methods.
But it can still cause the whole system to crash.
The problem becomes more complicated as the number of microservices increases. The number of microservices can be as high as 1000. This is where Hystrix comes in and we will use hystrix’s Fallback method functionality in this case. We have two services employee-Consumer that use services exposed by Employee-Consumer.
The simplified figure is shown below
Now suppose that for some reason the employee-producer exposed service throws an exception. We defined a fallback method in this case using Hystrix. This backup method should have the same return type as the exposed service. If an exception occurs in the exposed service, the fallback method returns some values.
# What is Hystrix circuit breaker? Do we need it?
For some reason, the Employee-Consumer exposure service throws an exception. Using Hystrix in this case we define a fallback method. If an exception occurs in the exposed service, the fallback method returns some default values.
If the exception in firstPage Method () continues, the Hystrix circuit will break and the employee users will collectively skip the firtsPage method and call the fallback method directly. The purpose of a circuit breaker is to allow time for the first page method or other methods that the first page method might call and cause an abnormal recovery. What may happen is that, with a low load, the problem that caused the exception has a better chance of recovery.
# What is Netflix Feign? What are its advantages?
Feign is a Java client interprogramming inspired by Retrofit, JAXRS-2.0, and WebSocket.
Feign’s first goal was to unify the complexity of the constraint denominator into the HTTP apis, regardless of its stability.
In the Employee-consumer example, we use the Employee-Producer REST service exposed using the REST template.
But we have to write a lot of code to perform the following steps
(1) Use functional zones for load balancing.
(2) Get the service instance, and then get the base URL.
(3) Use REST templates to use services. The previous code is as follows
@Controller
public class ConsumerControllerClient {
@Autowired
private LoadBalancerClient loadBalancer;
public void getEmployee() throws RestClientException, IOException {
ServiceInstance serviceInstance=loadBalancer.choose("employee-producer");
System.out.println(serviceInstance.getUri());
String baseUrl=serviceInstance.getUri().toString();
baseUrl=baseUrl+"/employee";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response=null;
try{
response=restTemplate.exchange(baseUrl,
HttpMethod.GET, getHeaders(),String.class);
}
catch (Exception ex)
{
System.out.println(ex);
}
System.out.println(response.getBody());
Copy the code
The previous code, with opportunities for exceptions like NullPointer, was not optimal. We’ll see how Netflix Feign can be used to make calling easier and cleaner. If the Netflix Ribbon dependency is also in the classpath, then Feign is also responsible for load balancing by default.
# What is Spring Cloud Bus? Do we need it?
Consider the following situation: we have multiple applications that use Spring Cloud Config to read properties, and Spring Cloud Config reads those properties from GIT.
The following example shows multiple Employee producer modules fetching Eureka registered properties from the Employee Config Module.
What happens if you assume that the Eureka registration property in GIT changes to point to another Eureka server. In this case, we would have to restart the service to get the updated properties.
There is another way to use executor endpoints/flushes. But we will have to call this URL separately for each module. For example, if Employee Producer1 is deployed on port 8080, http:// localhost: 8080 / refresh is called. Also for Employee Producer2 http://localhost:8081 / refresh, etc. That’s a hassle. This is where Spring Cloud Bus comes in.
Spring Cloud Bus provides the ability to refresh configurations across multiple instances. Therefore, in the example above, if we refresh Employee Producer1, all other required modules are automatically refreshed. This is especially useful if we have multiple microservices up and running. This is achieved by connecting all microservices to a single message broker. Whenever an instance is refreshed, this event subscribes to all microservices listening to this agent, and they are refreshed as well. The refresh of any single instance can be achieved by using endpoint/bus/refresh.
# The role of Spring Cloud circuit breaker
When a service calls another service due to network or its own problems, the caller will wait for the response of the called service. When more services request these resources, more requests wait, resulting in a chain effect (avalanche effect).
The circuit breaker has a fully open state: it cannot be called for a certain number of times within a period of time and there is no sign of recovery after repeated monitoring. The circuit breaker is fully open and the next request will not request the service
Half-open: The circuit breaker will send partial requests to the service if there are signs of recovery within a short period of time. The circuit breaker will close when it is called normally
Off: The service can be invoked when it is in the normal state
# What is Spring Cloud Config?
In a distributed system, due to a large number of services, a distributed configuration center is required to facilitate unified management and real-time update of service configuration files. In Spring Cloud, there is a distributed configuration center component, Spring Cloud Config, which enables configuration services to be placed in the memory of the configuration service (that is, locally) as well as in a remote Git repository. In the Spring Cloud Config component, there are two roles: Config Server and Config client.
Use:
(1) Add POM dependencies
(2) Add related configurations to the configuration file
(3) Add the @enableconFigServer annotation to the start class
# What is Spring Cloud Gateway?
Spring Cloud Gateway is the second generation of Spring Cloud’s official Gateway framework, replacing Zuul Gateway. As a traffic, the gateway plays a very important role in the micro-service system. The common functions of the gateway include routing and forwarding, permission verification, and traffic limiting control. Compiled a Java interview treasure book complete PDF
The RouteLocatorBuilder allows you to add various predicates and filters, based on the rules of the specific request. Filters are the kinds of filters used to make various judgments and changes to the request, processed by a specific route.