The architect will take you for an interview ②Spring Cloud interview questions

A summary of the Java interview, including basic Java knowledge, collection containers, concurrent programming, JVM, commonly used open source framework Spring, MyBatis, database, middleware, etc., including what you need or may use in the interview as a Java engineer Most knowledge. Everyone is welcome to read. I have limited knowledge, and there are inevitably mistakes or omissions in the blog I wrote. I hope you guys can give me advice. I am grateful. The article is continuously updated...

The architect takes you to review the interview series:

1. The architect will take you for an interview ①Spring Boot interview questions
Article list

Why do you need to learn Spring Cloud
What are the
design goals and advantages and disadvantages of Spring Cloud
Design goals
Advantages and disadvantages
Spring Cloud development prospects
Overall architecture
Main projects
Spring Cloud Config
Spring Cloud Netflix
Spring Cloud Bus
Spring Cloud Consul
Spring Cloud Security
Spring Cloud Sleuth
Spring Cloud Stream
Spring Cloud Task
Spring Cloud Zookeeper
Spring Cloud Gateway
Spring Cloud OpenFeign
Spring Cloud version relationship
Spring Cloud and Spring Boot version correspondence
Spring Cloud and each sub-project version correspondence relationship
What is the difference between Spring Boot and Spring Cloud ?
When using Spring Boot to develop distributed microservices, we face the following questions.
What does service registration and discovery mean? How to implement Spring Cloud?
What is the difference between Spring Cloud and dubbo?
What is the meaning of load balancing?
What is Hystrix? How does it achieve fault tolerance?
What is a Hystrix circuit breaker? Do we need it?
What is Netflix Feign? What are its advantages?
What is Spring Cloud Bus? Do we need it?
The role of Spring Cloud circuit breaker
What is Spring Cloud Config?
What is Spring Cloud Gateway?

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: The business is complex, resulting in a large amount of code, and management will become increasingly 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, and it is difficult to avoid code conflicts. The development process will be accompanied by the process of continuously resolving conflicts, which will seriously affect the development efficiency; the
cost of troubleshooting and solving problems is high: the online business finds bugs, and the process of fixing the bugs 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 it 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 the development convenience of Spring Boot 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 large backing and can ensure subsequent updates and improvements
. It has 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 highly active, with rich tutorials, and it is easy to find solutions when encountering problems.
Service splitting has finer granularity and low coupling, which is beneficial Reuse of resources is conducive to improving development efficiency. It
can make more precise and optimized service plans and improve the maintainability of the system
. It can reduce the cost of the team. It can be developed in parallel. You don't need to pay attention to how other people develop. First, focus on your own development
microservices. Platform, it can be developed in any language
Suitable for the Internet era, the 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.) challenges the team.
In general, the advantages outweigh the disadvantages. At present, it seems that Spring Cloud is a very With a complete distributed framework, it is obvious that many companies have begun to use microservices and Spring Cloud. 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 server software system technology level.

Overall structure
Insert picture description here
main items

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 component, including server-side registry and client-side service discovery mechanism;
Ribbon: load-balanced service invocation component, with multiple load-balancing invocation strategies;
Hystrix: service fault-tolerant component, which implements the circuit breaker mode for dependent services error and delay in providing fault tolerance;
Feign: Ribbon and Hystrix based declarative service call component;
Zuul: API gateway component to requests for routing and filtering capabilities.
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
Insert picture description here
Spring Cloud and each sub-project version correspondence

Insert picture description here
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.

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 found 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.
Insert picture description here
Suppose if the microservice 9 in the figure above fails, then we will propagate an exception using traditional methods. 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.
Insert picture description here
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.
Insert picture description here
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.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-nMSJX6ml-1582105816943)(https://user-gold-cdn.xitu.io/2019/12/30 /16f55fbfd4e33ae7?imageView2/0/w/1280/h/960/format/webp/ignore-error/1)]

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.
Insert picture description here
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.
Insert picture description here
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 fully open, so the next request will not request the service

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 is 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.

The official account of this blog: Muzi network side business, welcome to pay attention to the exchange!

Guess you like

Origin blog.csdn.net/ncw8080/article/details/113946179