Continuing updates…

springboot

Question: Introduce the followingSpringBootApplicationComments? And automatic configuration?

Answer: SpringBootApplication is a composite annotation, consisting of three annotations. Annotating it triggers autoconfiguration (@enableautoconfiguration) and ComponentScan (@componentscan).

  • @componentScan Scans all components in the package and subpackages of the current configuration class by default. Exclude excludes the main startup class and auto configuration class

  • @Configuration annotates Configuration classes, but @SpringBootConfiguration does not substantially extend them.

  • EnableAutoConfiguration The key to autoconfiguration is that this annotation consists of the following two components

    @AutoConfigurationPackage
    @Import(AutoConfigurationImportSelector.class)
    public @interface EnableAutoConfiguration
    Copy the code
    • @AutoConfigurationPackage

      / / that contains the annotation of class in the package should be registered in AutoConfigurationPackages. @Import(AutoConfigurationPackages.Registrar.class) public @interface AutoConfigurationPackageCopy the code

      The main startup class must be at the top of the package for all custom components so that Spring can scan for them. That’s what it does.

    • @ Import (AutoConfigurationImportSelector. Class) will Import AutoConfigurationImportSelector class. Performs selectImports method, this method will eventually call SpringFactoriesLoader. LoadFactoryNames method, A similar SPI mechanism loads the spring.factories file from meta-INF /spring.factories, with the contents of the Properties file. Key is org. Springframework. Boot. Autoconfigure. EnableAutoConfiguration specify all the automatic configuration of class (is a big string, it is automatically configured class’s fully qualified class name), the assembly to the IOC container, The autoconfiguration class is then created using ImportSelector and @import.

spring cloud Netflix

Would you please say something abouteurekaWhat are the common configuration items?

A: The configuration items provided by Eureka fall into three categories:

  • One is used to control the behavior of the Eureka server, beginning with Eureka.
  • One is to consider the configuration requirements from the client perspective, starting with eureka. Client.
  • The last class, on the other hand, focuses on the service instance itself registered to Eureka, beginning with eureka.instance.

Note that Eureka, in addition to acting as a server-side component, can actually be registered with Eureka itself as a client, in which case it uses the client-side configuration items

Common configurations of a single node are as follows:

Server: port: 8761 // Eureka: client: registerWithEureka: false ServiceUrl: defaultZone: http://localhost:8761 // The configuration item is used for service addresses. This is useful for building Eureka server clustersCopy the code

Common cluster configurations: The cluster is in Peer to Peer mode. application-eureka1.yml

Server: port: 8761 Eureka: instance: hostname: eureka1 client serviceUrl defaultZone: http://eureka2:8762 /eureka/ // Is used to point to other Eureka servers in the clusterCopy the code

application-eureka2.yml

Server: port: 8762 Eureka: instance: hostname: eureka2 client serviceUrl defaultZone: HTTP: / / http://eureka1:8761/eureka/ / / the other had been used to point to the cluster serverCopy the code

Can you talk about it or draw a picture of iteurekaArchitecture concept?

A:EurekaThe following concepts are directly related to service governance: service registration, service renewal, service cancellation, and service rejection.

  • Service Register Service Register is the most basic concept of service governance. Each microservice embedded in the Eureka client provides basic information related to service discovery, such as IP address and endpoint, to the Eureka server to complete service registration.

  • Service renewal The Eureka client interacts with the server through a short connection. Therefore, the Eureka client needs to proactively report its runtime status at regular intervals for service renewal.

  • Cancel a service. Cancel is when the Eureka client notifies the Eureka server that it no longer wants to register with Eureka

Where does Eureka keep the registration information? In what data structure?

A: Registration information is stored in memory. The InstanceRegistry interface implementation class AbstractInstanceRegistry has discovered a data structure that Eureka uses to store registration information. It is a two-layer ConcurrentHashMap:

private final ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>> registry = new ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>>();
Copy the code

The Key of the first layer ConcurrentHashMap is spring.application.name, which is the name of the service, and the Value is a ConcurrentHashMap. In the second layer ConcurrentHashMap, the Key is instanceId, which is the unique instanceId of the service, and the Value is the Lease object. Eureka uses the term Lease to represent an abstraction of service registration information. The Lease object holds service instance information and the time associated with the registration of some instance services. Such as the registration time registrationTimestamp, the latest renewal time lastUpdateTimestamp, etc.

How to understandEurekaHigh availability?

A: Had a highly available deployment way called Peer Awareness model, can see from PeerAwareInstanceRegistryImpl class had service registration, registration will be call replicateToPeers method of nodes, That is, to synchronize to other Eureka nodes.

@Override public void register(final InstanceInfo info, final boolean isReplication) { int leaseDuration = Lease.DEFAULT_DURATION_IN_SECS; if (info.getLeaseInfo() ! = null && info.getLeaseInfo().getDurationInSecs() > 0) { leaseDuration = info.getLeaseInfo().getDurationInSecs(); } super.register(info, leaseDuration, isReplication); ReplicateToPeers (action.register, info.getAppName(), info.getid (), info, null, replicateToPeers) isReplication); }Copy the code

What is theAP? Compare a common service registry?

A: AP means that when we ask the registry for a list of services, we can tolerate the registry to return registration information that is several minutes old, but we cannot accept that the service is directly down and unavailable. In other words, the service registry facility requires more availability than consistency.

  • Zookeeper ensures that when the master node loses contact with other nodes due to a network fault, the remaining nodes will re-elect the leader. The problem is that it takes 30 to 120s to elect the leader, and the entire ZK cluster is unavailable during the election, which leads to the breakdown of the registration service during the election. In the cloud deployment environment, it is highly likely that the ZK cluster will lose its master node due to network problems. Although the service can be restored eventually, it is intolerable that the registration is not available for a long time due to the long election time.

  • Eureka ensures that all AP Eureka nodes are equal. The failure of a few AP Eureka nodes does not affect the work of other AP Eureka nodes. The remaining AP Eureka nodes can still provide registration and query services. If an Eureka client fails to register with an Eureka, it will automatically switch to another node. As long as there is one Eureka available, the registration service will be available, but the information may not be up to date (no strong consistency is guaranteed). In addition, Eureka has a self-protection mechanism. If more than 85% of the nodes do not have a normal heartbeat within 15 minutes, Eureka considers that the network between the client and the registry has failed. In this case, the following conditions can occur:

    • Eureka will no longer remove services from the registration list that should expire because they have not received a heartbeat for too long
    • Eureka will still accept registration and query requests for new services, but it will not be synchronized to other nodes (i.e. the current node is still available).
    • When the network is stable, the new registration information of the current instance is synchronized to other nodes

    As a result, Eureka is able to cope with a network failure that causes some nodes to lose contact, rather than breaking down the entire registration service like ZooKeeper. Eureka guarantees high availability (A) and final consistency:

    • Registering services is relatively fast, because you don’t have to wait to register replicates on other nodes, and there’s no guarantee that you can register replicates successfully.
    • In case of data inconsistency, although the registration information on A and B is not identical, each Eureka node can still provide services normally. In this case, if A cannot find the service information when requesting A, B can find the service information. This ensures usability but sacrifices consistency.
  • Consul guarantees CP Consul is written in the GO language with a built-in service registration and discovery framework, distributed consistency protocol implementation, health check, Key/Value storage, and multi-data center solutions. The Raft algorithm is used, which is simpler than the Paxos algorithm used by ZooKeeper. Although strong consistency is guaranteed, availability decreases accordingly. For example, service registration takes a little longer because Consul’s RAFT protocol requires more than half of the nodes to be successfully written. After the leader fails, the Consul service becomes unavailable before the leader is elected. So, Consul strong consistency (C) brings:

    • Service registration is slightly slower than Eureka. Consul’s RAFT protocol requires that more than half of the nodes are written successfully before the registration is considered successful.
    • When the Leader is down, consul is unavailable during re-election. Strong consistency is guaranteed but usability is sacrificed.
  • Nacos guarantees CP + AP Nacos supports dynamic configuration of services in addition to registration discovery of services. Dynamically configured services allows you to manage application and service configurations for all environments in a centralized, externalized, and dynamic manner. Dynamic configuration eliminates the need to redeploy applications and services when configuration changes occur, making configuration management more efficient and agile. Centralized configuration management makes it easier to implement stateless services and make it easier to scale services flexibly on demand. Nacos = Spring Cloud Registry + Spring Cloud Configuration Center

What are the load balancing policies in the Ribbon? Which is the default?

A: Load balancing algorithms can be classified into static load balancing algorithms and dynamic load balancing algorithms.

  • Static load balancing algorithms are easy to understand and implement. Typical load balancing algorithms include Random, Round Robin, and Weighted Round Robin.

    Note: All static algorithms involving weights can be converted to dynamic algorithms because weights can be updated dynamically during operation. For example, in the dynamic polling algorithm, the weight value is constantly updated based on the continuous monitoring of each server.

  • Dynamic algorithms include source IP hash algorithm, minimum number of connections algorithm, and service call delay algorithm.

The default load balancing policy is a polling policy.

Q: WhyRestTemplateAdd a @loadBalanced annotation and load balancing is automatically implemented?

Q: Can you briefly describe Zuul?

A: Zuul is an API gateway whose main functions areRequest monitoring, security management, routing rules, logging, access control, and service adaptation, and other functions. A gateway can act as a gateway between a client and a microserviceThe separation. The division and implementation of the various microservices behind the gateway may need to be adjusted and upgraded as business requirements change and evolve over time. Such tweaks and upgrades should be transparent to the client.You need to add a dependency

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
Copy the code

The EnableZuulProxy annotation needs to be added to the initiator.

Question: How to use itZuulImplement service routing?

A: Service routing means that requests accessed through Zuul are routed and forwarded to the corresponding back-end service. Zuul service visit the URL of the common format: http://zuulservice:5555/service, including zuulservice representative Zuul server address. In this case, the determination of the back-end service corresponding to the service depends on the service routing information located in Zuul. There are three ways:

  • Mapping service routes based on service discovery because when Zuul starts, it obtains information about all currently registered services from Eureka, and then automatically generates mapping relationships between service names and target services. For example, the back-end services are configured as follows

    spring:
       application:
               name: userservice
    Copy the code

    We can access to the service through http://zuulservice:5555/userservice, notice that the URL of the target service is userservice, consistent with the name of the service definition. Through access to the Zuul service routing endpoint http://localhost:5555/actuator/routes to get the service route map information.

  • Mapping service Routing based on dynamic configuration Automatic mapping based on the above service discovery mechanism is simple to use, but has limitations, such as not using the default service name to name the target service, or adding a uniform Prefix before each request path. The above does not work, so you need to implement service routing based on dynamic configuration mapping. This approach needs to be configured in the application.yml file

    Zuul: prefix: / springHealth // add a prefix that identifies a module or subsystem. Routes: ignored-services: 'userService' // Ignores external use of routes automatically mapped by the system userService: /user/**Copy the code

    Here we use /user to specify the request root address for user-service. Now when we visit http://zuulservice:5555/springhealth/user/, is equivalent to the request sent to the userservice instance in Eureka.

  • Mapping service routing based on static configuration Both of the above methods are dependent on the EureKA service registry. For example, if we need to access a third-party service, the service cannot be registered with our EuREka registry, but it exposes an HTTP endpoint for us to call. At this point, static mapped service routing can be used.

    zuul:
      routes:
        thirdpartyservice:
          path: /thirdpartyservice/**
              url: http://thirdparty.com/thirdpartyservice
    Copy the code

    Such access/thirdpartyservice / * *, Zuul the request will be forwarded to the outside of the third party service http://thirdparty.com/thirdpartyservice. If we also need load balancing when mapping service routes using static configuration, we can use the ribbon to do this:

    zuul: routes: thirdpartyservice: path: /thirdpartyservice/** serviceId: thirdpartyservice ribbon: eureka: enabled: False // Close the association between the Ribbon and Eureka because the static service is not registered on Eureka. Thirdpartyservice: Ribbon: // Manually specify the list of Ribbon services listOfServers: http://thirdpartyservice1:8080,http://thirdpartyservice2:8080Copy the code

Q: How does Zuul work?

A: The process of Zuul responding to HTTP requests is a typical filter structure, and the ZuulFilter component is provided internally to implement this mechanism. IZuulFilter is an interface, and ZuulFilter is a direct subclass of IZuulFilter.

Public interface IZuulFilter {// Determines whether the filter should be executed. In general, this method returns true Boolean shouldFilter(); // This Filter specifies the business logic to be implemented. Object run() throws ZuulException; } public abstract class ZuulFilter implements IZuulFilter, Comparable<ZuulFilter> { .... Public abstract String filterType(); public abstract String filterType(); Public abstract int filterOrder(); . }Copy the code

With filters, there should be a component in the system that manages the filters, called the FilterRegistry

Public class FilterRegistry {// Create FilterRegistry instance using the classic singleton pattern. private static final FilterRegistry INSTANCE = new FilterRegistry(); public static final FilterRegistry instance() { return INSTANCE; } // Inside FilterRegistry, you can see that the thread safe ConcurrentHashMap is used to cache ZuulFilter directly. private final ConcurrentHashMap<String, ZuulFilter> filters = new ConcurrentHashMap<String, ZuulFilter>(); private FilterRegistry() { } public ZuulFilter remove(String key) { return this.filters.remove(key); } public ZuulFilter get(String key) { return this.filters.get(key); } public void put(String key, ZuulFilter filter) { this.filters.putIfAbsent(key, filter); } public int size() { return this.filters.size(); } public Collection<ZuulFilter> getAllFilters() { return this.filters.values(); }}Copy the code

Q: What configuration will your Feign do in production?

A: This configuration is usually done:

Feign: client: config: default: connectTimeout: 5000 Httpclient: enabled: false // Disable httpClient okhttp: enabled: Compression: request: enabled: true # Enable compression mime types: text/xml,application/xml,application/json #min-request-size: 2048 response: enabled: true hystrix: enabled: True // Enable the ribbon: eureka: enabled: true // Enable the ribbon ReadTimeout: 200000 ConnectTimeout: 100000 MaxAutoRetries: 0 / / the same instance maximum retries, not including was first called MaxAutoRetriesNextServer: 1 / / try again other instances of maximum retries, not including the selected server OkToRetryOnAllOperations for the first time: Hystrix: threadPool: default: coreSize: 1000 ## Maximum number of concurrent threads to execute, default: 10 The maximum number of queue 1000 # # BlockingQueue queueSizeRejectionThreshold: 500 # # even maxQueueSize not reached, after reaching queueSizeRejectionThreshold the value, the request will be reject the command: default: execution: isolation: thread: timeoutInMilliseconds: 110000Copy the code

So, it’s usually configured

  • Configure the connection timeout and read timeout of the request.
  • Shut downhttpclientOpen,okhttpfeign.okhttp.enabled=true ,feign.httpclient.enabled=false
  • Enabling the Ribbon
  • Configure the Hystrix. Hystrix is used to implement the functions such as circuit breaker, overload protection, and resource isolation between microservices. Therefore, configure the number of threads in the Hystrix thread pool and the maximum number of queues in BlockingQueue.

Question: Please describe the following Hystrix, what does it have?

A: juejin. Cn/post / 684490…

Spring Cloud Alibaba