Preface:
Today, I woke up and found that our start date was delayed again. Although we have been working from home for more than a week, we still couldn’t work efficiently due to the environment at home. So I just sorted out some knowledge points of Spring Cloud.
We sorted out some Spring Cloud related interview questions and tested our knowledge of Spring Cloud to see the self-test results.
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, message bus, load balancing, circuit breakers, data monitoring, etc., which can be started and deployed with one click using Spring Boot’s development style.
What are the advantages of using Spring Cloud?
When developing distributed micro-services using Spring Boot, we face the following issues
-
Complexity associated with distributed systems – this overhead includes network issues, latency costs, bandwidth issues, and security issues.
-
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.
-
Redundancy – The problem of redundancy in distributed systems.
-
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.
-
Performance – Issues Performance issues due to various operational overhead.
-
Deployment complexity -Devops skills required.
How does Spring Cloud implement service registration and discovery?
-
Spring Cloud automatically registers a service to a registry (Eureka or Zookeeper) by specifying a service name (including IP address and port) when it is published. Simply add @enableDissCoveryClient to the main method to enable multiple instances of the same service modification port.
-
Call method: Pass the service name to retrieve all available instances through the registry and invoke the corresponding service (Ribbon and Feign) through load balancing policies.
Why use Spring Cloud fuses?
When a service calls another service, due to network reasons or their own reasons, the caller will wait for the response of the called, when more services request to these resources, resulting in more requests to wait, so that there will be a chain effect, circuit breaker is to solve this problem.
The status of a circuit breaker is as follows:
-
Fully open: within a certain period of time, the service cannot be called for a certain number of times, and there is no sign of recovery after repeated tests, the circuit breaker is fully open, then the next request will not request the service.
-
Half-open: After a short period of recovery, the breaker will send part of the request to the service. When it can be called normally, the breaker will close.
-
Off: The service is always in the normal state and can be invoked normally. The circuit breaker is off.
What do I mean by service registration and discovery? 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.
Is Spring Cloud different from Dubbo?
-
Service invocation dubbo is the RPC SpringCloud Rest Api
-
Registries, Dubbo is Zookeeper and SpringCloud is Eureka, which can also be ZooKeeper
-
Springcloud has Zuul routing gateway, which acts as a routing server for consumer request distribution. Springcloud supports circuit breakers, perfect integration with Git configuration files to support version control. The transaction bus implements a series of microservice architecture elements such as configuration file update and automatic service assembly.
How do microservices communicate independently
1. Remote Procedure Invocation (Invocation) : Service Invocation via Remote Procedure Invocation.
Advantages:
- Simple and common, the system is simpler because there is no middleware proxy
Disadvantages:
- Only request/response patterns are supported, and nothing else is supported, such as notification, request/asynchronous response, publish/subscribe, and publish/asynchronous response
- Availability is reduced because both the client and the server must be available during the request
2. Messaging: Use asynchronous messaging to communicate between services. Services communicate by exchanging messages through message pipes.
Advantages:
-
Decouple the client side from the server side, making it more loosely coupled
-
Improved availability because messaging middleware caches messages until consumers can consume them
-
Supports many communication mechanisms such as notification, request/asynchronous response, publish/subscribe, and publish/asynchronous response
Disadvantages:
- Message-oriented middleware has additional complexity
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 usually involves proprietary software or hardware, such as multi-tier switches or domain name System service processes.
How do microservices communicate independently?
1. Remote calls, such as feign calls, directly access other services through remote procedure calls. 2. Message middleware
How does springcloud implement service registration?
1. When the service is published, specify the corresponding service name and register the service with the registry (Eureka Zookeeper).
2. Add @enableeurekaserver to the registry. The service uses @enableDiscoveryClient.
What does the Spring Cloud circuit breaker do?
In a distributed architecture, the breaker mode works similarly. When a service unit fails (similar to a short circuit in an appliance), the breaker’s fault monitoring (similar to blowing a fuse) returns an error response to the caller, rather than waiting for a long time. In this way, threads will not be held for a long time due to invocation of faulty services, and the spread of faults in distributed systems is avoided.
What is the Hystrix?
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, there are many microservices involved that work with each other, and the problem becomes more complex as the number of microservices increases. We will use Hystrix’s Fallback method to handle this, assuming that for some reason the exposed service interface throws an exception, in which case we define a Fallback method using Hystrix. The fallback method should have the same return type as the exposed service, and if an exception occurs in the exposed service, the fallback method will return the corresponding information.
Eureka and ZooKeeper both provide service registration and discovery functions. Please explain the differences between the two
-
ZooKeeper guarantees CP,Eureka guarantees AP. ZooKeeper’s registration service crashed during the election. Although the service will eventually be restored, it will not be available during the election. All Eureka nodes are equal, as long as there is one Eureka, the service can be available. The data queried is not the latest self-protection mechanism, so Eureka will no longer remove the service that should expire due to the long time without heartbeat from the registered list. Eureka can still accept registration and query requests for new services, but they are not synchronized to other nodes (highly available). When the network is stable, the new registration information of the current instance is synchronized to other nodes (final consistency). Eureka can cope with the loss of some nodes due to network failure without causing the entire registration system to collapse like ZooKeeper.
-
ZooKeeper functions as Leader and Follower. All Eureka nodes are equal
-
ZooKeeper adopts the principle of more than half survival, while Eureka adopts the self-protection mechanism to solve the partition problem
-
Eureka is essentially a project, whereas ZooKeeper is just a process
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
- Use functional zones for load balancing.
- Get the service instance, and then get the base URL.
- Use REST templates to use services. The previous code is as follows
@Controller
public class ConsumerControllerClient {
@Autowired
private LoadBalancerClient loadBalancer;
public void getEmployee(a) 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.
REST vs. RPC
1. The main defect of RPC is that there is too strong dependence between the service provider and the calling method. It is necessary to define the interface of each micro-service and publish through continuous inheritance so that strict version control can avoid conflicts.
2.REST is a lightweight interface. There is no coupling between the provision and invocation of services and only a convention is required for specification.
What is a feigin? What are its advantages?
-
Feign uses interface-based annotations
-
Feign integrates the Ribbon with load balancing capabilities
-
Integrated with Hystrix, with fuse breaker capability
Use:
1. Add POM dependencies.
2. Add @enableFeignClients to the startup class
3. Define an interface @feignClient (name= “XXX”) to specify which service to invoke
What’s the difference between the Ribbon and Feign?
-
The Ribbon calls other services, but in different ways.
-
The Ribbon is @ribbonClient feign and the Ribbon is @enableFeignClients
-
The Ribbon is declared on the @RibbonClient annotation, while Feign uses the @FeignClient declaration in the interface that defines the abstract method.
-
The Ribbon builds HTTP requests, simulates HTTP requests, and sends them to other services using the RestTemplate. Feign needs to define the method to be called as an abstract method.
What is Spring Cloud Bus?
Spring Cloud Bus connects distributed nodes with lightweight message brokers that can be used to broadcast configuration file changes or direct communication with services, as well as for monitoring.
If you change the configuration file, send a request and all clients re-read the configuration file.
Use:
1. Add dependencies
2. Configuration rabbimq
Eureka and ZooKeeper both provide service registration and discovery functions. What is the difference between the two?
Zookeeper is based on the CP principle, with strong consistency and fault tolerance of partitions.
Eureka is AP principle availability and partition fault tolerance.
Zookeeper When the primary node is faulty, zK selects the primary node again on other nodes, which takes a long time. Although the primary node is recovered, services are unavailable during the primary node selection, which is unacceptable.
All eureka nodes are equal. If one node fails, the other nodes still provide normal services.
What do you know about the microservices tech stack? 1 evels
The role of the service gateway
-
Simplify client call complexity and process external requests in a unified manner.
-
Data pruning and aggregation: according to different interface requirements, data processing and external.
-
Multi-channel support, providing different gateway support for different clients.
-
Microservitization of legacy systems can be used as the transfer components of new and old systems.
-
Unified handling of security and permission issues during invocation.
Link tracing Sleuth
When Spring Cloud Sleuth was introduced in our project, each link request would add a string of trace information in the format [server-name, main-traceid, sub-SPANID, Boolean] :
-
Server-name: indicates the name of a service node.
-
Main-traceid: indicates the unique ID of a link. The ID is traceId.
-
Sub-spanid: Indicates the spanId of each link.
-
Boolean: Whether to output information to services such as Zipkin for collection and display.
Sleuth is implemented based on HTTP. To ensure that data collection does not affect normal services, Sleuth adds important information about tracing requirements to the Header of each request. In this way, during data collection, only the relevant information on the Header needs to be sent to the corresponding image tool. The image tool analyzes and displays the uploaded data according to the logic corresponding to Span.
Well, everyone, that’s the end of this article! If there are any mistakes in this article, please comment, appreciate!
I'm Timo! A flood of moral integrity, a awe-inspiring, upright Java programmer