Summary of java microservice interview questions: Spring Cloud interview questions summary (with answer analysis)

Preface

Some interview questions collected in the latest 2020 (all organized into documents), there are a lot of dry goods, including
detailed explanations of netty, spring, thread, spring cloud, etc., there are also detailed learning plans, interview questions, etc. I feel that I am in the interview. Speaking very clearly: to get the interview information, just: click here to get it!!! Password: CSDNInsert picture description here

1. What is Spring Cloud?

The Spring cloud streaming application launcher is a Spring integrated application of Spring Boot, which provides integration with external systems. Spring cloud Task, a short life cycle microservice framework, is used to quickly build applications that perform limited data processing.

2. What are the advantages of using Spring Cloud?

When using Spring Boot to develop distributed microservices, we face the following problems
(1) the complexity associated with distributed systems-this overhead includes network issues, latency 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-The problem is the performance problem caused by various operating expenses.
(6) Requirements for deploying complex evops skills.

3. What does service registration and discovery mean? How to achieve 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 properties becomes more complicated. Some services may drop, and some locations may change. Changing the attributes manually may cause problems. Eureka service registration and discovery can help in this situation. Since all services are registered on the Eureka server and searched by calling the Eureka server, there is no need to deal with any changes and processing of the service location.

4. 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 multilayer switches or domain name system server processes.

5. What is Hystrix? How does it achieve fault tolerance?

Hystrix is ​​a latency and fault-tolerant library designed to isolate access points to remote systems, services, and third-party libraries. When a failure is an inevitable failure, it stops cascading failures and achieves resilience in complex distributed systems. Usually, for systems developed using microservices, many microservices are involved. These microservices cooperate with each other. Consider the following microservices.

Suppose that if the microservice 9 in the above figure 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 that use the service exposed by employee-consumer. The simplified diagram is shown below.

Now suppose that due to reasons, 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.

6. What is Hystrix circuit breaker? Do we need it?

For some reasons, the employee-consumer public service will throw an exception. In this case, using Hystrix we define 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, Hystrix will be powered on, and the employee user will skip the firstPage method and call the fallback method directly. The purpose of the circuit breaker is to allow time for the first 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.

7. What is Netflix Feign? What are its advantages?

Feign is a java client-side binder 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 employee-consumer example, we used the REST service exposed by the emplo e-producer using the REST template.
But we have to write a lot of code to perform the following steps
1, use the functional area 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 Fe n to make calls easier and cleaner. If Netflix Ribbon is in the dependency path, Feign will also load balance by default.

8. What is Spring Cloud Bus? Do we need it?

Consider the following situation: We have multiple applications using Spr ng Cloud Config to read attributes, and S ring Cloud Config reads these attributes from GIT.
In the following example, multiple employee producer modules obtain Eureka registered properties from the Employee Config Module

. What happens if the Eureka registered 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. Also 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, if we refresh Employee Producer1, all other necessary modules will be automatically refreshed. This is especially useful if we have a microservice 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. Refresh to any single instance can be achieved by using endpoint/bus/refresh

9. What is a microservice

Microservice architecture is an architectural pattern or architectural style. It advocates dividing a single application into a set of small services. Each service runs in its own independent process, and the services coordinate and interact with each other. Cooperate to provide users with ultimate value. The services use a lightweight communication mechanism to communicate with each other (usually HTTP-based RESTful API). Each service is built around a specific business and can be independently built in a production environment, a production-like environment, etc. In addition, a unified and centralized service management mechanism should be avoided. For a specific service, the appropriate language and tools should be selected according to the business context to build it. A very lightweight centralized management can be used. To coordinate these services, you can use different languages ​​to write services, or you can use different data stores.

10. What is a service circuit breaker? What is service degradation

The fuse mechanism is a microservice link protection mechanism to deal with the avalanche effect. When a microservice is unavailable or the response time is too long, the service will be degraded, and the call of the microservice of the node will be fuse, and the "error" response message will be returned quickly. When it is detected that the microservice call response of the node is normal, the call link is restored. In the SpringCloud framework, the fuse mechanism is implemented by Hystrix. Hystrix will monitor the status of calls between microservices. When the failed calls reach a certain threshold, the default is 20 calls within 5 seconds. If it fails, the fuse mechanism will be activated.
Service degradation is generally considered from the overall load. That is, when a service is broken, the server will no longer be called. At this time, the client can prepare a local fallback callback and return a default value. In this way, although the level is reduced, it is usable at any rate, which is better than hanging up directly.

11. Both Eureka and zookeeper can provide service registration and discovery functions, please tell us the difference between the two?

Zookeeper guarantees CP (C: consistency, P: partition fault tolerance), Eureka guarantees AP (A: high availability)
(1) When querying the registry for the service list, we can tolerate the registry returning a few minutes ago The information, but can not tolerate the unavailability of direct down. In other words, the service registration function has high requirements for high availability, but zk will have such a situation, when the master node loses contact with other nodes due to a network failure, the remaining nodes will re-select the leader. The problem is that the leader selection time is too long, 30 ~ 120s, and the zk cluster is unavailable during the selection period, which will cause the registration service during the selection period to be paralyzed. In a cloud deployment environment, it is a high probability that the zk cluster will lose the master node due to network problems. Although the service can be restored, the long-term unavailability of registration caused by the long selection time cannot be tolerated.
(2) Eureka guarantees usability. Each node of Eureka is equal. The failure of several nodes will not affect the work of normal nodes. The remaining nodes can still provide registration and query services. When Eureka's client registers or discovers a certain Eureka, if the connection fails, it will automatically switch to other nodes. As long as one Eureka is still there, the registration service can be guaranteed to be available, but the information found may not be the latest. In addition, Eureka also has a self-protection mechanism. If more than 85% of the nodes do not have a normal heartbeat within 15 minutes, then Eureka believes that the client and the registry have a network failure. At this time, the following situations will occur:
①, Eureka will not remove the services that should expire because they have not received heartbeats for a long time from the registration list.
②, Eureka can still accept new service registration and query requests, but it will not be synchronized to other nodes (that is, to ensure that the current node is still available)
③, when the network is stable, the new registration information of the current instance will be synchronized to other nodes . Therefore, Eureka can deal with the situation that some nodes lose contact due to network failures, and will not paralyze the entire microservice like Zookeeper.

12. 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 to provide configuration management, service discovery, circuit breakers, routing, microagents, Event bus, global lock, decision-making campaign, distributed conversation and other integrated services 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. SpringCloud pays attention to the global governance framework

13. What is a Hystrix circuit breaker? Do we need it

For some reasons, the employee-consumer public service will cause an exception. In the case of using Hystrix, we define 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 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.

14. Talk about the implementation principle of RPC

First of all, there needs to be a module to handle network connection communication, responsible for connection establishment, management and message transmission. Secondly, there needs to be a codec module, because network communications are all bytecodes for transmission, and we need to serialize and deserialize the objects we use. The rest is the client and server parts. The server exposes the service interface to be opened. The client calls a proxy implementation of the service interface. This proxy implementation is responsible for collecting data, encoding and transmitting to the server and waiting for the result to return.

15. The advantages and disadvantages of microservices? What are the pits encountered in development projects?

Advantages:
(1) Each service is directly cohesive enough, and the code is easy to understand.
(2) The development efficiency is high. One service can only do one thing, which is suitable for small teams to develop.
(3) Loosely coupled and functional services.
(4) It can be developed in different languages ​​and interface-oriented programming.
(5) Easy for third-party integration
(6) Microservices are just business logic codes, and will not
be combined with HTML, CSS or other circles (7) Can be flexibly matched with public libraries/connected independent libraries
Disadvantages:
(1) Distributed system Responsibility
(2) The difficulty of multi-service operation and maintenance has increased.
(3) System deployment dependence, communication cost between services, data consistency, system integration testing, performance monitoring.

16. What is the difference between spring cloud and d bbo?

(1) The service calling method dubbo is RPC spri cloud Rest Api
(2) Registration center, dubbo is zookeeper, 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, perfectly integrated with git, configuration files support version control, transaction bus implementation of configuration file update and service automatic assembly, etc. A series of micro Service architecture elements.

17. Comparison of REST and RPC

(1) The main defect of RPC is that the dependency between the service provider and the calling method is too strong. It is necessary to define the interface of each microservice and release it through continuous inheritance, so that strict version control will not conflict.
(2) REST is a lightweight interface. There is no code coupling between service provision and invocation, and only a convention is required for specification.

18. What microservice technology stack do you know?

Dimension (springcloud)
service development: springboot spring springmvc
service configuration and management: Archaiusm of Netfix, Diamond
service registration and discovery of Ali : Eureka, Zookeeper
service call: Rest RPC gRpc
service fuse: Hystrix
service load balancing: Ribbon Nginx
service interface Call: Fegin
message queue: Kafka Rabbitmq activemq
service configuration center management: SpringCloudConfig
service routing (API gateway) Zuul
event message bus: SpringCloud Bus

19.How do microservices communicate independently?

(1) Remote calls, such as feign calls, directly access other services through remote procedure calls.
(2) Message middleware

20. How does springcloud realize service registration?

(1) When the service is released, specify the corresponding service name and register the service to the registry (eureka zookeeper)
(2) Add @EnableEurekaServer to the registry, use @EnableDiscoveryClient for the service, and then use ribbon or feign to directly call the service discovery.

21, the difference between Eureka and Zookeeper

(1) Eureka takes the AP of CAP and pays attention to availability, while Zookeeper takes the CP of CAP and pays attention to consistency.
(2) Zookeeper registration service is paralyzed during the election period. Although the service will eventually be restored, it will be unavailable during the election period.
(3) Eureka's self-protection mechanism will lead to a result that services that expire due to not receiving a heartbeat for a long time will not be removed from the registration list. Registration and query requests for new services can still be accepted, but they will not be synchronized to other nodes. No service will be paralyzed.
(4) Zookeeper has the roles of Leader and Follower, and all nodes of Eureka are equal.
(5) Zookeeper adopts the principle of more than half survival, and reka adopts self-protection mechanism to solve the partition.
(6) Eureka is essentially a project, and Zookeeper is just a process.

22. What is eureka's self-protection mechanism?

When Eureka Server loses too many instances of connections in a short period of time (such as network failure or frequent startup and shutdown of the client), the node will enter the self-protection mode, protect the registration information, no longer delete the registration data, and automatically exit when the failure is restored Self-protection mode.

23. What is Ribbon?

ribbon is a load balancing client, which can well control some behaviors of htt and tcp. Feign integrates ribbon by default.

24. What is feigin? What are its advantages?

(1) feign uses interface-based annotations
(2) feign integrates ribbon and has the ability to load balance
(3) integrates Hystrix and has the ability to fuse.
Use:
(1) Add pom dependency.
(2) Add @EnableFeignClients to the startup class
(3) Define an interface @FeignClient(name="xxx") to specify which service to call

25. The difference between Ribbon and Feign?

(1) Ribbon calls other services, but in different ways.
(2) The startup class annotations are different, Ribbon is @RibbonClient feign is @EnableFeignClients
(3) The service specified location is different, Ribbon is declared on the @RibbonClient annotation, and Feign uses the @FeignClient declaration in the interface that defines the abstract method.
(4) The calling method is different. Ribbon needs to construct an http request by itself, simulate the http request and then use the RestTemplate to send it to other services. The steps are quite complicated. Feign needs to define the called method as an abstract method.

26. What is Spring Cloud Bus?

The spring cloud bus connects distributed nodes with a lightweight message broker. It can be used to broadcast configuration file changes or direct service communication, as well as monitoring.
If you modify the configuration file and send a request once, all clients will read the configuration file again.
Use:
(1) Add dependency
(2) Configure rabbimq

27. What does the springcloud circuit breaker do?

When a service calls another service due to network or self-cause problems, the caller will wait for the caller's response. When more service requests to these resources cause more requests to wait, a chain effect (avalanche effect)
circuit breaker occurs There is a fully open state: it cannot be called a certain number of times within a period of time and there is no sign of recovery for many times. The circuit breaker is completely open, then the next request will not request the service.Half
open: there is a sign of recovery in a short time. Part of the request is sent to the service, and the circuit breaker is closed
when it is called normally. Closed: When the service has been in a normal state, it can be called

28、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. The meaning of predicates assertions is that, as the name implies, it is processed by specific routes according to specific request rules, and filters are various filters. The device is used to make various judgments and modifications to the request.

29. As a service registration center, how is Eureka better than Zookeeper?

(1) Eureka guarantees availability and partition fault tolerance, while Zookeeper guarantees consistency and partition fault tolerance.
(2) Eureka also has a self-protection mechanism. If more than 85% of the nodes do not have a normal heartbeat within 15 minutes, then Eureka believes that there is a network failure between the client and the registry. It will not paralyze the entire registration service like zookeeper.

30. What is Ribbon load balancing?

(1) Spring Cloud Ribbon is a set of client load balancing tools based on Netflix Ribbon.
(2) The Ribbon client component provides a series of complete configuration items such as connection timeout, retry, etc. Simply put, it is to list all the machines behind Load Balancer (LB) in the configuration file, and Ribbon will automatically help you connect these machines based on certain rules (such as simple polling, random connection, etc.). It is also easy to use Ribbon to implement custom load balancing algorithms.

31. What can Ribbon load balancing do?

(1) Distribute user requests equally to multiple services.
(2) Centralized LB means using independent LB facilities (hardware, such as F5, or software) between consumers and providers of services , Such as nginx), the facility is responsible for forwarding the access request to the service provider through a certain strategy;
(3) In-process LB integrates the LB logic into the consumer, and the consumer knows which addresses are available from the service registry, and then Then choose a suitable server from these addresses.
Note: Ribbon belongs to the in-process LB, it is just a class library, integrated in the consumer process, and the consumer gets the address of the service provider.

32. What is Zuul routing gateway

(1) Zuul contains the two most important functions of request routing and filtering: it is responsible for forwarding external requests to specific microservice instances, which is the basis for realizing a unified entry for external access, while the filter function is responsible for request processing Intervention in the process is the basis for realizing functions such as request verification and service aggregation.
(2) Zuul and Eureka integrate, register Zuul itself as an application under Eureka service governance, and obtain other microservice messages from Eureka. That is to say, all future visits to microservices are obtained after Zuul jumps.
Note: Zuul service will eventually be registered into Eureka to provide three functions = proxy + routing + filtering

33. What can the distributed configuration center do?

(1) Centralized management of configuration files, different configurations in different environments, dynamic configuration updates, and deployment by environment such as
dev/test/prod/beta/release
(2) Dynamic adjustments during operation, no longer need to deploy machines in each service Write the configuration file on the above, the service will pull the configuration information from the configuration center.
(3) When the configuration changes, the service does not need to restart to sense the configuration change and apply the new configuration. The configuration information will be in the form of a REST interface Exposed

34, Hystrix related solutions

@EnableHystrix: Turn on the fuse
@HystrixCommand(fallbackMethod=”XXX”): Declare a failure rollback processing function XXX, when the annotated method execution timeout (default is 0 milliseconds), the fallback function will be executed and an error message will be returned.

35. Both Eureka and zookeeper can provide service registration and discovery functions. Could you tell me the difference between the two?

Zookeeper guarantees CP (C: consistency, P: partition fault tolerance), Eureka guarantees AP (A: high availability)
(1) When querying the registry for the service list, we can tolerate the registry returning a few minutes ago The information, but can not tolerate the unavailability of direct down. That is to say, the service registration function has relatively high requirements for high availability, but zk will have such a situation, when the master node loses contact with other nodes due to a network failure, the remaining nodes will reselect the leader. The problem is that the leader selection time is too long, 30 ~ 120s, and the zk cluster is not available during the selection period, which will cause the registration service during the selection period to be paralyzed. In a cloud deployment environment, it is a high probability that the zk cluster will lose the master node due to network problems. Although the service can be restored, the long-term unavailability of registration caused by the long selection time cannot be tolerated.
(2) Eureka guarantees availability. Eureka's nodes are equal. The failure of several nodes will not affect the work of normal nodes. The remaining nodes can still provide registration and query services. When Eureka's client registers or discovers a certain Eureka, if the connection fails, it will automatically switch to other nodes. As long as one Eureka is still there, the registration service can be guaranteed to be available, but the information found may not be the latest. In addition, Eureka also has a self-protection mechanism. If more than 85% of the nodes do not have a normal heartbeat within 15 minutes, then Eureka believes that the client and the registry have a network failure. At this time, the following situations will occur:
①, Eureka will not remove from the registration list services that should expire because they have not received heartbeats for a long time.
②, Eureka can still accept new service registration and query requests, but it will not be synchronized to other nodes (that is, to ensure that the current node is still available)
③, when the network is stable, the new registration information of the current instance will be synchronized to other nodes .
Therefore, Eureka can deal with the situation that some nodes lose contact due to network failures, and will not paralyze the entire microservice like Zookeeper.

At last

Guess you like

Origin blog.csdn.net/weixin_50917449/article/details/109249453