Shock! Hanging the interviewer, the necessary SpringCloud microservice interview questions (VIP Collection Edition)

Table of contents

Spring Cloud microservice interview questions

1. What components are included in Spring Cloud Netflix and Spring Cloud Alibaba

2. Is Nacos CP or AP?

3. Should Nacos choose CP or AP as the registration center?

4. How does Nacos achieve nearby access?

5. The underlying principle of Nacos underlying load balancing

6. Nacos1.x registration center architecture process

7. Nacos2.X as a registration center architecture process

8. Distro protocol in Nacos

9. Principle of Eureka Registration Center

10. Principle of Eureka self-protection mechanism

11. Comparison between Eureka and Nacos

12. Nacos configuration center long polling mechanism

13. The timed task referenced by Nacos configuration fails (Nacos encounters problems during work)

14. What configurations does Nacos load, and what is the priority of these configurations?

15. The Nacos configuration center is down, will it affect the service?

16. Technical selection of configuration center

17. Why does Feign take a long time to call for the first time?

18. How does Feign realize the transfer of certification?

19. What is Feign's bottom layer to send HTTP by default? What's the problem? How can we improve?

20. Please briefly describe the 2PC process and its advantages and disadvantages

21. Please briefly describe the 3PC process and its advantages and disadvantages

22. What transaction modes does Seata support?

23. How to transfer xid globally through Feign in Seata

24. Gateway core concept

25. How to achieve smooth service migration in Gateway?

26. Zuul architecture and how to ensure thread safety

27. The difference between Zuul startup annotations @EnableZuulProxy and @EnableZuulServer


  1. Spring Cloud Netflixand Spring Cloud Alibabawhich components are included

  2. Is Nacos CP or AP?

  3. Should Nacos choose CP or AP as the registration center?

  4. How does Nacos implement nearby access?

  5. The underlying principle of Nacos underlying load balancing

  6. Nacos1.x registration center architecture process

  7. Nacos2.X as a registration center architecture process

  8. Distro protocol in Nacos

  9. Principle of Eureka Registration Center

  10. Principle of Eureka self-protection mechanism

  11. Comparison between Eureka and Nacos

  12. Nacos configuration center long polling mechanism

  13. The timed task that references the Nacos configuration fails (Nacos encounters problems in its work)

  14. Nacos loads those configurations, and the priority of these configurations?

  15. The Nacos configuration center is down, will it affect the service?

  16. Technical selection of configuration center

  17. Why does Feign take a long time to call for the first time?

  18. How does Feign realize the transfer of certification?

  19. What is Feign's bottom layer to send HTTP by default? What's the problem? How can we improve?

  20. Please briefly describe the 2PC process and its advantages and disadvantages

  21. Please briefly describe the 3PC process and its advantages and disadvantages

  22. What transaction modes does Seata support?

  23. How to transfer xid globally through Feign in Seata

  24. Gateway core concept

  25. How to implement smooth service migration in Gateway?

  26. Zuul architecture and how to ensure thread safety

  27. Zuul startup annotations @EnableZuulProxy and @EnableZuulServerdifferences


1. What components are included in Spring Cloud Netflix and Spring Cloud Alibaba

Spring Cloud Netflix is ​​mainly composed of:  Eureka, Ribbon, Feign, Hystrix, Zuul|Gateway, Config and other components.

Spring Cloud Alibaba is mainly  composed of Nacos, Sentinel, Seata and other components.

2. Is Nacos CP or AP?

Nacos can guarantee both CP and AP. It depends on how to configure it. The default is AP mode.

3. Should Nacos choose CP or AP as the registration center?

CP:  If the registry belongs to CP, when we register an instance with the registry or remove an instance, we have to wait for the data in the registry cluster to be consistent before the registration or removal is successful, which is time-consuming. As the scale of business applications increases and applications go online and offline frequently, the pressure on the registration center will be relatively high, which will affect the efficiency of service discovery and service invocation.

AP:  If the registration center is an AP, the registration center cluster can provide services no matter what happens, even if there is an inconsistency in the data between nodes, for example, a service node that has been offline is pulled, but now the general Microservice frameworks or components provide service fault tolerance and retry functions, which can also avoid this problem. For the registration center, it does not need to consume too many resources to ensure data consistency in real time, and it is enough to ensure the final consistency, so that the pressure on the registration center will be less.

4. How does Nacos achieve nearby access?

In Nacos, a service can have multiple instances, and it can be set for the instance cluster-name. If a service A wants to call service B, then Naocs will see which cluster the instance calling service A belongs to, and call the same cluster. The instance of service B, this is the nearest access of Nacos.

5. The underlying principle of Nacos underlying load balancing

It is implemented through the Ribbon. The load balancing algorithm is defined in the Ribbon, and then an instance is obtained from the service instance based on these algorithms to provide services.

6. Nacos1.x registration center architecture process

  1. When the service is started, service registration is initiated through the api.

  2. Service consumers will pull the list of services they want to use when they start.

  3. Service consumers will pull data every 10 seconds.

  4. When the Nacos service detects an abnormality (the service goes offline), it will send the UDP protocol to the client for update.

  5. The service will send heartbeats to Nacos every 5 seconds.

  6. Nacos checks the heartbeat information every 5 seconds to determine whether it has timed out. If it exceeds 15 seconds, it sets the node to an unhealthy state and broadcasts it. If it exceeds 30 seconds, it removes the node, indicating that the node is unavailable.

  7. Nacos cluster data synchronization task protocol: Distro(AP) , Raft(CP)

7. Nacos2.X as a registration center architecture process

8. Distro protocol in Nacos

  • Each node in Nacos is responsible for part of the write requests.

  • Each node will synchronize the new data it is responsible for to other nodes.

  • Each node regularly sends the check value of its own data to other nodes to maintain data consistency.

  • Each node independently processes read requests and sends responses locally in a timely manner.

  • The newly added Distro node will pull the full amount of data.

9. Principle of Eureka Registration Center

  • The service starts to register.

  • Data synchronization within the cluster.

  • The client timing task pulls data every 30s.

  • The client heartbeat renews the contract every 30s.

  • Check whether the instance is expired every minute, remove it if it is expired, and enter self-protection if a large number of disconnections occur.

  • Call the API to go offline gracefully.

10. Principle of Eureka self-protection mechanism

The Eureka server will check the normal heartbeat ratio of all Eureka instances every 15 minutes, and if it is lower than 85%, it will trigger the self-protection mechanism. When the protection mechanism is triggered, Eureka will temporarily protect these failed services from expiration, but these services will not never expire.

After the startup is complete, Eureka will check the health status of the service every 60 seconds. If the services that have been protected and failed after a period of time (90 seconds by default) are still not restored, these services will be removed. If the service is restored during this period and the heartbeat ratio of the instance is higher than 85%, the self-protection mechanism will be automatically turned off.

11. Comparison between Eureka and Nacos

  • In Nacos2.0, the registration center will actively push information to consumers regularly, but Eureka will not actively push information.

  • Nacos supports CP and AP modes, and Eureka supports AP modes.

  • Nacos has elegant service online and offline and traffic management, while Eureka's background page is only for display, needs to use api to operate online and offline and does not have traffic management function.

  • The Nacos community is active, and the Eureka open source work has stopped.

  • Nacos integrates the registration center and configuration center functions, and Eureka is just a registration center.

12. Nacos configuration center long polling mechanism

Nacos 1.4.x

The client will poll and send a long connection request to the server. This long connection will time out at most 30s. The server will first judge whether there is a configuration update when it receives the request from the client, and return immediately if there is no server. Request to join the queue "hold" for 29.5s, and then check the configuration file in the last 0.5s and return normally regardless of whether the configuration file is updated. However, during the waiting period of 29.5s, if there is a configuration update, it can end early and return.

Nacos2.x

  • After the configuration of the server is changed, the client is notified of the service change through the long link, and the client then pulls it.

  • Timed tasks are pulled every 5 seconds.

13. The timed task referenced by Nacos configuration fails (Nacos encounters problems during work)

  1. First of all, we need to know that @Schedule uses the post-processor when loading the bean ScheduledAnnotationBeanPostProcessor, gets @Schedulethe marked method and then executes it in the life cycle of the bean.

  2. @RefreshScopeThere is a @Scope in which the value is Refresh. He creates the object and puts it in the corresponding cache. We GenericScope#getobtain the corresponding Bean object from the cache through the method. When updating the configuration and refreshing the container, these instance objects will be cleared and called. If @RefreshScopemarked There is a scheduled task in the object @Schedule, so we can't continue to access it. We need to call an interface in the instance to create the corresponding instance ( BeanFactory#getBean if there is a corresponding object, it will be obtained, and if there is no corresponding object, it will be created), and then the corresponding scheduled task will be normal operation.

Solution: After updating the configuration and refreshing the container RefreshScopeRefreshedEvent, an event will be sent. We only need to listen to this event, and then it will create a corresponding instance, and then the scheduled task can be executed normally.

14. What configurations does Nacos load, and what is the priority of these configurations?

  • sharedConfigs Public configuration, such as redis, mysql configuration.

  • extensionConfigs Extended configuration files.

  • ${application.name} nacos-config

  • ${application.name}. ${file-extension} nacos-config.yaml

  • ${application.name}- ${profile}. ${file- extension} nacos-config-prod.yaml

15. The Nacos configuration center is down, will it affect the service?

Won't. After the client obtains the configuration information of the configuration center, it will save a copy of the configuration information locally. When the configuration center is down, it will read the local file first.

16. Technical selection of configuration center

  • Pay attention to community activity.

  • Combine your own technology stack.

  • Whether the product function is satisfied.

17. Why does Feign take a long time to call for the first time?

The ribbon is lazy-loaded by default, and the components corresponding to the ribbon will only be generated when it is called for the first time, which will cause the problem that the first call will be very slow.

ribbon:
  eager-load:
    enabled: true
      clients: service-1

18. How does Feign realize the transfer of certification?

Implement the interface RequestInterceptorand pass the authentication through the header.

public class FeignAuthRequestInterceptor implements RequestInterceptor {
private String tokenId;

public FeignAuthRequestInterceptor(String tokenId) {
    this.tokenId = tokenId;
}

@Override
public void apply(RequestTemplate template) {
    template.header("Authorization",tokenId);
}

}

19. What is Feign's bottom layer to send HTTP by default? What's the problem? How can we improve?

The bottom layer of Feign comes with JDK by default HttpURLConnection. It sends HTTP requests with a single thread and cannot configure thread pool. We can use Okhttp or HttpClient to send http requests, and both of them support thread pool.

Common HTTP Clients

  • HttpClient

HttpClient is  Apache Jakarta Common a sub-project under Http, which is used to provide an efficient, up-to-date, feature-rich client programming toolkit supporting the Http protocol, and it supports the latest version and recommendations of the HTTP protocol. Compared with the traditional JDK  URLConnection, HttpClient improves the ease of use and flexibility, makes it easier for the client to send HTTP requests, and improves the efficiency of development.

  • Okhttp

An open source project for processing network requests, is the most popular lightweight framework on the Android side, contributed by Square, used to replace  HttpUrlConnection and  Apache HttpClient. OkHttp has a concise API, efficient performance, and supports multiple protocols (HTTP/2 and SPDY).

  • HttpURLConnection

HttpURLConnection It is a standard class of Java, which it inherits from  URLConnection, and can be used to send GET requests and POST requests to specified websites. HttpURLConnection It is more complicated to use, not as easy to use as HttpClient.

  • RestTemplate

RestTemplate It is a client provided by Spring for accessing Rest services. RestTemplate It provides a variety of convenient methods for accessing remote HTTP services, which can greatly improve the writing efficiency of clients.

Okhttp configuration

feign:
  okhttp:
    enabled: true

20. Please briefly describe the 2PC process and its advantages and disadvantages

Advantages:  Try to ensure the strong consistency of the data, and the implementation cost is low. It has its own implementation in all major mainstream databases. For MySQL, it supports (XA) from 5.5.

shortcoming:

  • Single point problem:  The role of the transaction manager in the whole process is very critical. If it goes down, for example, the first phase has been completed, and the transaction manager is down when the second phase is preparing to submit, the resource manager will Blocked all the time, making the database unusable.

  • Synchronous blocking:  After being ready, the resources in the resource manager are blocked until the submission is completed and the resources are released.

  • Data inconsistency:  Although the two-phase commit protocol is designed for the strong consistency of distributed data, there is still the possibility of data inconsistency. Only some participants received and executed the commit operation, while the rest of the participants have been blocked because they did not receive the notification, and data inconsistency occurred at this time.

21. Please briefly describe the 3PC process and its advantages and disadvantages

Three-phase commit (3PC) is an upgraded optimization of two-phase commit (2PC), and 3PC inserts a preparation phase into the first and second phases of 2PC. It is guaranteed that the state of each participant node is consistent before the final submission stage.

At the same time, a timeout mechanism is introduced in both the coordinator and the participant. When the participant fails to receive the commit request from the coordinator for various reasons, the local transaction will be aborted without being blocked and waiting, which solves the single point of failure problem of 2PC , but 3PC still fails to fundamentally solve the problem of data consistency.

Advantages:  Introducing a timeout mechanism. Solved the problem that the resource is always blocked due to the sudden downtime of the transaction manager.

Disadvantages:  3PC uses a timeout mechanism to solve the problem of synchronous blocking, but at the same time, there is one more network communication, the performance becomes worse, and the problem of data inconsistency still exists.

22. What transaction modes does Seata support?

Provides four modes of 2PC

  • AT mode:  Provides a transaction mode without intrusion and automatic compensation [here is based on a relational database that can support transactions locally, and then java code can access the database through JDBC, here is no intrusion: we only need to add corresponding annotations to open the global Affairs]

  • XA mode:  supports the XA mode of the database that has implemented the XA interface [here generally requires the database to implement the corresponding XA mode interface, generally like mysql oracle has implemented XA]

  • TCC mode:  TCC can be understood as 2PC at the application level, which requires us to write business logic to achieve it.

  • SAGA mode:  Provides an effective solution for long transactions.

23. How to transfer xid globally through Feign in Seata

The global transaction id is passed through Feign's header.

24. Gateway core concept

  • route

Routing is the most basic part of a gateway. Routing information includes an ID, a destination URI, a set of predicate factories, and a set of Filters. If the predicate is true, the requested URL matches the configured route.

  • predicates

That is java.util.function.Predicate , Spring Cloud Gateway uses Predicate to implement routing matching conditions.

  • Filter

The filters in SpringCloud Gateway are divided into Gateway FilIer and Global Filter. Filter can process requests and responses.

Routes are forwarding rules, predicates are the conditions for whether to follow this path, filters can add business logic to routes, modify requests and responses

25. How to achieve smooth service migration in Gateway?

You can use the assertion factory of the Weight route to configure the service weight, and put the configuration in the Nacos configuration center for dynamic migration.

Weight routing assertion factory: The assertion factory contains two parameters, which are used to represent the group group and weight. For multiple uri addresses in the same group, the router will forward the request to the corresponding uri in proportion according to the set weight. Achieve load balancing.

spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: https://weighthigh.org
        predicates:
        - Weight=group1, 8
      - id: weight_low
        uri: https://weightlow.org
        predicates:
        - Weight=group1, 2

26. Zuul architecture and how to ensure thread safety

Servlets are not thread-safe, and they will pass through data. The filter has a very troublesome thing, that is, how does the filter distinguish each request?

Zuul is used  RequestContextto pass data between filters. The data is stored in the ThreadLocal of each request, including where the request is routed to, HttpServletRequest, HttpServletResponse etc. These data are stored in the RequestContext.

Summary: Our Zuul is composed of many filters. These filters are divided into pre-routing filters, post-routing filters, and routing filters in routing. Although servlets, runners, and filters are all thread-unsafe, we is RequestContextthread-safe.

27. The difference between Zuul startup annotations @EnableZuulProxy and @EnableZuulServer

We generally introduce @EnableZuulProxy that this @EnableZuulServerclass inherits the corresponding class and adds its functions.


Follow the WeChat public account: Recharge your resources Reply
: Spring
[imooc-java2021] System Course-Java Engineer 2022 Edition
Quark network disk: https://pan.quark.cn/s/bbaec39732e0#/list/share

 

Pay attention to the official account, all the resources you want are available, and there are so many resources for free and pure sharing
 

Guess you like

Origin blog.csdn.net/CDB3399/article/details/130887809