Why you need to learn Spring Cloud
Regardless of whether it is a commercial application or a user application, it is very simple at the beginning of the business, and we usually implement it as a monolithic application. However, with the gradual development of business, product ideas will become more and more complex, and the application of monolithic structures will become more and more complex. This will bring the following problems to the application:
- code structure is chaotic: business is complex, resulting in a large amount of code, management will become more and more difficult. At the same time, this will also bring huge challenges to the rapid iteration of the business;
- development efficiency becomes low: developers develop a set of codes at the same time, it is difficult to avoid code conflicts. The development process will be accompanied by the process of constantly resolving conflicts, which will seriously affect the development efficiency;
- troubleshooting and solving the problem is costly: online business found a bug, the process of fixing the bug may be very simple. However, because there is only one set of code, it needs to be recompiled, packaged, and online, which is very costly.
As the application of the monolithic structure increases with the increase in system complexity, various problems will be exposed. In recent years, the microservice architecture has gradually replaced the monolithic architecture, and this trend will become more and more popular. Spring Cloud is currently the most commonly used microservice development framework and has been widely used in enterprise-level development.
What is Spring Cloud
Spring Cloud is an ordered collection of a series of frameworks. It uses Spring Boot's development convenience to cleverly simplify the development of distributed system infrastructure, such as service discovery registration, configuration center, intelligent routing, message bus, load balancing, circuit breakers, data monitoring, etc., all of which can be used by Spring Boot The development style enables one-click startup and deployment.
Spring Cloud does not repeat the manufacturing of wheels. It just combines the relatively mature and practical service frameworks developed by various companies, and uses Spring Boot style to repackage and shield the complex configuration and implementation principles, and finally develop The authors set aside a set of distributed system development kits that are easy to understand, easy to deploy, and easy to maintain.
Design goals and advantages and disadvantages
Design goals
Coordinate various microservices and simplify the development of distributed systems.
Pros and cons
There are so many microservice frameworks such as: dubbo, Kubernetes, why use Spring Cloud?
advantage:
- Produced in the Spring family, Spring is unmatched in the enterprise-level development framework. It has a big backing and can guarantee subsequent updates and improvements.
- Rich components and complete functions. Spring Cloud provides very complete support for the microservice architecture. For example, configuration management, service discovery, circuit breakers, microservice gateways, etc.;
- The Spring Cloud community is very active, with rich tutorials, and it is easy to find solutions when encountering problems
- Service splitting has finer granularity and lower coupling degree, which is conducive to resource reuse and improves development efficiency
- Can more accurately formulate optimized service plans and improve the maintainability of the system
- Reduce the cost of the team, you can develop in parallel, do not need to pay attention to how other people develop, 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:
- Too many microservices and high governance costs are not conducive to maintaining the system
- The high cost of distributed system development (fault tolerance, distributed transactions, etc.) poses a big challenge to the team
Generally speaking, the advantages outweigh the disadvantages. At present, it seems that Spring Cloud is a very complete distributed framework. At present, many companies start to use microservices and the advantages of Spring Cloud are obvious. Therefore, for students who want to study microservice architecture, learning Spring Cloud is a good choice.
Spring Cloud development prospects
Spring Cloud is a boon for small and medium-sized Internet companies, because such companies often do not have the strength or sufficient funds to develop their own distributed system infrastructure. Using Spring Cloud one-stop solution can calmly deal with business Greatly reduce development costs while developing.
At the same time, with the popularity of the microservice architecture and Docker container concept in recent years, Spring Cloud will also have a place in the increasingly "cloud" software development style in the future, especially in the diverse distributed solutions. With a standardized, full-site technical solution, the significance may be comparable to the birth of the Servlet specification in the past, effectively promoting the progress of the technical level of the server software system.
Overall structure
main project
The sub-projects of Spring Cloud can be roughly divided into two categories. One category is the encapsulation and abstraction of the existing mature framework "Spring Boot", and is also the largest number of projects; the second category is the development of a part of the infrastructure of a distributed system Realization, for example, Spring Cloud Stream plays a role such as kafka and ActiveMQ.
Spring Cloud Config
Centralized configuration management tool, unified external configuration management in a distributed system, Git is used by default to store configuration, which can support client configuration refresh and encryption and decryption operations.
Spring Cloud Netflix
Netflix OSS open source component integration, including core components such as Eureka, Hystrix, Ribbon, Feign, Zuul, etc.
- Eureka: service management components, including the server-side registry and the client-side service discovery mechanism;
- Ribbon: Load balancing service invocation component, with multiple load balancing invocation strategies;
- Hystrix: Service fault-tolerant component, which implements the circuit breaker mode, and provides fault tolerance for errors and delays in dependent services;
- Feign: Declarative service invocation component based on Ribbon and Hystrix;
- Zuul: API gateway component, which provides routing and filtering functions for requests.
Spring Cloud Bus
The message bus used to propagate cluster status changes, using a lightweight message agent to link nodes in a distributed system, can be used to dynamically refresh the service configuration in the cluster.
Spring Cloud Consul
Service governance component based on Hashicorp Consul.
Spring Cloud Security
The security toolkit supports the load balancing OAuth2 client and login authentication in Zuul proxy.
Spring Cloud Sleuth
The distributed request link tracking of Spring Cloud applications supports the use of Zipkin, HTrace, and log-based (such as ELK) tracking.
Spring Cloud Stream
A lightweight event-driven microservice framework that can use a simple declarative model to send and receive messages, mainly implemented as Apache Kafka and RabbitMQ.
Spring Cloud Task
It is used to quickly build a microservice framework for short-lived, limited data processing tasks, and is used to add functional and non-functional features to applications.
Spring Cloud Zookeeper
Service management component based on Apache Zookeeper.
Spring Cloud Gateway
The API gateway component provides routing and filtering functions for requests.
Spring Cloud OpenFeign
The declarative service invocation component based on Ribbon and Hystrix can dynamically create an interface implementation based on Spring MVC annotations for service invocation. In Spring Cloud 2.0, it has replaced Feign as a first-class citizen.
Spring Cloud version relationship
Spring Cloud is a comprehensive project composed of many sub-projects, and each sub-project has a different release rhythm. In order to manage the version dependency between Spring Cloud and each sub-project, a list is released, which includes the sub-project version corresponding to a certain Spring Cloud version.
In order to avoid confusion between the Spring Cloud version number and the sub-project version number, the Spring Cloud version uses names instead of version numbers. The names of these versions use the names of London Underground stations, corresponding to the time sequence of the versions according to the alphabetical order, for example Angel is the first version, and Brixton is the second version.
When the release of Spring Cloud reaches a critical point or a major bug is resolved, a "service releases" version, referred to as the SRX version, will be released. For example, Greenwich.SR2 is the second SRX version of the Greenwich version released by Spring Cloud. The latest version of Spring Cloud is Hoxton.
Spring Cloud and SpringBoot version correspondence
Correspondence between Spring Cloud and each sub-project version
Note: Hoxton version is based on SpringBoot 2.2.x version and does not apply to 1.5.x version. As the SpringBoot 1.5.x version stops maintenance in August 2019, the Edgware version will also stop maintenance.
What is the difference between SpringBoot and SpringCloud?
SpringBoot focuses on the rapid and convenient development of individual individual microservices.
SpringCloud is a microservice coordination and management framework that focuses on the overall situation. It integrates and manages individual microservices developed by SpringBoot.
Provide integrated services between various microservices, such as configuration management, service discovery, circuit breakers, routing, microagents, event bus, global locks, decision-making campaigns, distributed conversations, etc.
SpringBoot can leave SpringCloud to use development projects independently, but SpringCloud cannot do without SpringBoot, which belongs to the relationship of dependency
SpringBoot focuses on the rapid and convenient development of individual microservices, and SpringCloud focuses on the global service governance framework.
When using Spring Boot to develop distributed microservices, we face the following problems
(1) Complexity related to distributed systems-this overhead includes network issues, delay overhead, bandwidth issues, and security issues.
(2) Service discovery-The service discovery tool manages how processes and services in the cluster are searched and talked to each other. It involves a service catalog, registering services in the catalog, and then being able to find and connect to the services in the catalog.
(3) Redundancy-Redundancy problems in distributed systems.
(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-problems Performance problems caused by various operating expenses.
(6) Deployment complexity-Devops skill requirements.
What does service registration and discovery mean? How to implement Spring Cloud?
When we start a project, we usually do all the configuration in the properties file. As more and more services are developed and deployed, adding and modifying these attributes becomes more complicated. Some services may drop, and some locations may change. Changing the properties manually may cause problems.
Eureka service registration and discovery can help in this situation. Since all services are registered on the Eureka server and the search is completed by calling the Eureka server, there is no need to deal with any changes and processing of the service location.
What is the difference between Spring Cloud and dubbo?
(1) The service calling method dubbo is RPC springcloud Rest Api
(2) Registration center, dubbo is zookeeper and springcloud is eureka, or zookeeper
(3) Service gateway, dubbo itself is not implemented, and 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 and is perfectly integrated with git. Configuration file support version Control, transaction bus to achieve configuration file update and service automatic assembly, and a series of microservice architecture elements.
What is the significance of load balancing?
In computing, load balancing can improve the workload distribution across multiple computing resources such as computers, computer clusters, network links, central processing units, or disk drives. Load balancing aims to optimize resource usage, maximize throughput, minimize response time and avoid overloading any single resource. Using multiple components for load balancing rather than a single component may increase reliability and availability through redundancy. Load balancing usually involves dedicated software or hardware, such as multi-layer switches or domain name system server processes.
What is Hystrix? How does it achieve fault tolerance?
Hystrix is a latency and fault-tolerant library designed to isolate the access points of remote systems, services and third-party libraries. When failures are inevitable, stop cascading failures and achieve resilience in complex distributed systems.
Usually for a system developed using a microservice architecture, many microservices are involved. These microservices cooperate with each other.
Consider the following microservices
Suppose if the microservice 9 in the above figure fails, then we will propagate an exception using the traditional method. But this will still cause the entire system to crash.
As the number of microservices increases, this problem becomes more complicated. The number of microservices can be as high as 1000. This is where hystrix appears. We will use Hystrix's Fallback method in this case. We have two services employee-consumer using the service exposed by employee-consumer.
The simplified diagram is shown below
Now suppose that for some reason, the service exposed by employee-producer throws an exception. We use Hystrix in this case to define a fallback method. This fallback method should have the same return type as the public service. If an exception occurs in the exposed service, the fallback method will return some value. [
What is a Hystrix circuit breaker? Do we need it?
For some reasons, the employee-consumer exposed service will throw an exception. In this case, using Hystrix we have defined a fallback method. If an exception occurs in the public service, the fallback method returns some default values.
If the exception in the firstPage method() continues to occur, the Hystrix circuit will be interrupted, and the employee user will skip the firtsPage method together and call the fallback method directly. The purpose of the circuit breaker is to allow time for the first page method or other methods that the first page method may call, and cause abnormal recovery. What may happen is that under a small 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 binding program inspired by Retrofit, JAXRS-2.0 and WebSocket.
Feign's first goal is to unify the complexity of the constraint denominator to http apis, regardless of its stability.
In the example of employee-consumer, we use the REST service exposed by employee-producer using a REST template.
But we have to write a lot of code to perform the following steps
(1) Use functional areas for load balancing.
(2) Get the service instance, and then get the basic URL.
(3) Use the REST template to use the service. 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());
}
The previous code, with exceptions like NullPointer, is not optimal. We will see how to use Netflix Feign to make calls easier and cleaner. If the Netflix Ribbon dependencies are also in the classpath, Feign will also be 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 these properties from GIT.
In the following example, multiple employee producer modules obtain Eureka registered properties from the Employee Config Module.
What happens if you assume that the Eureka registration properties in GIT are changed to point to another Eureka server. In this case, we will have to restart the service to get the updated properties.
There is another way to use actuator endpoint/refresh. But we will have to call this url separately for each module. For example, if Employee Producer1 is deployed on port 8080, call http://localhost:8080/refresh. The same for Employee Producer2 http://localhost:8081/refresh and so on. This is troublesome again. This is where Spring Cloud Bus comes into play.
Spring Cloud Bus provides the function of refreshing configuration across multiple instances. Therefore, in the above example, if we refresh Employee Producer1, all other necessary modules will be refreshed automatically. 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 the instance is refreshed, this event will be subscribed to all microservices listening to this agent, and they will also be refreshed. The refresh of any single instance can be achieved by using the endpoint/bus/refresh. [
The role of Spring Cloud circuit breakers
When a service calls another service due to network reasons or its own reasons, the caller will wait for the callee's response. When more services request these resources, more requests will be waited, and a chain effect (avalanche effect) will occur.
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 multiple monitoring. The circuit breaker is completely open, then the service will not be requested next time.
Half-open: There is a sign of recovery in a short time, the circuit breaker will send part of the request to the service, and the circuit breaker will be closed during normal calls
Closed: When the service has been in a normal state, it can be called normally
What is Spring Cloud Config?
In a distributed system, due to the huge number of services, in order to facilitate the unified management and real-time update of service configuration files, a distributed configuration center component is required. In Spring Cloud, there is a distributed configuration center component spring cloud config, which supports the configuration service in the memory of the configuration service (that is, local), and also supports the remote Git warehouse. In the spring cloud config component, there are two roles, one is config server, and the other is config client.
use:
(1) Add pom dependency
(2) Add related configuration to the configuration file
(3) Add annotation @EnableConfigServer to the startup class
What is Spring Cloud Gateway?
Spring Cloud Gateway is the second-generation gateway framework officially launched by Spring Cloud, replacing Zuul gateway. As 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 current limiting control.
A RouteLocatorBuilder bean is used to create routes. In addition to creating routes, RouteLocatorBuilder allows you to add various predicates and filters. Predicates means assertions. As the name implies, it is processed by specific routes according to specific request rules. Filters are various filters. The device is used to make various judgments and modifications to the request.
Author: ThinkWon
Source: https://thinkwon.blog.csdn.net/article/details/104397367This article was first published on the public account: Java Edition web project, welcome to pay attention to get more exciting content
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。