Brother, brother, you secretly read my blog, the interviewer will not be angry, if he knew I gave you such detailed information, he will not beat me. Interviewer, unlike me, I only feel bad

Spring Cloud

The five components

Eureka service registration and discovery

  1. Service governance

In the traditional RPC remote call framework, it is complicated to manage each service and the dependency relationship between services, so it is necessary to use service governance to manage the dependency relationship between services, which can realize service invocation, load balancing, fault tolerance, etc., and realize service discovery and registration. 2. Service Registration Because Eureka adopts CS design architecture, Eureka Server serves as the Server of service registration function, which is the service registry. Other microservices in the system use Eureka to connect to Eureka Server and maintain heartbeat connections. In this way, the maintenance personnel of subsystems can monitor the normal operation of each micro-service in the system through Eureka Server. In service registration and discovery, there is a registry. When the server is started, it aliases the information about the current server to the registry, such as the service address and communication address. Another party (consumer | service provider), in the form of the alias registry access to the actual service address, and then realize the local RPC calls RPC remote calls his framework core design idea: lies in the registry, because use registry management a dependency between each service and the service (service governance concept). In the how to RPC remote framework, there is always a registry (holding service address related information (interface address))

Eureka architecture vs. Dubbo architecture

    

  1. Eureka protection mode

Overview: The protection mode is used when network partitions exist between a group of clients and the Eureka Server. Once in protected mode, Eureka Server will attempt to protect the information in its service registry and will not delete the data in the service registry, that is, will not unregister any microservices. Belongs to the AP branch in CAP.

This message is displayed on the Eureka Server home page, indicating that Eureka is in protected mode.

cause

  1. Why does Eureka self-protection arise?

In order to prevent EurekaClient from running normally but being disconnected from EurekaServer, EurekaServer will not remove EurekaClient immediately. 2. What is self-protection mode? By default, EurekaServer will log out of a microservice instance if it does not receive a heartbeat for a certain amount of time (90 seconds by default). However, when the network partition failure occurs (delay, lag, congestion), the microservice and EurekaServer cannot communicate normally, the above behavior becomes dangerous — because the microservice itself is healthy, the microservice should not be logged out at this time. Eureka solves this problem by going into “self-protected mode” — when a EurekaServer node loses too many clients in a short period of time (possibly due to a network partition failure), the node goes into self-protected mode.

In self-protected mode, Eureka Server protects the information in the registry and does not unregister any service instances. The design philosophy is that it is better to retain incorrect service registration information than blindly unregister any healthy service instances. Self-protection mode is a security protection measure against network exceptions. Using self-protection mode can make Eureka cluster more robust and stable.

Enable self-preservation to ensure that the unusable services are removed in time. False EurekaServer Service registry: add @enableeurekaserver EurekaClient to the primary startup class

Ribbon load balancing service invocation

  1. An overview of the

The Ribbon is an open source project released by Netfix. It provides client-side software load balancing algorithms and service invocation. The Ribbon client component provides a comprehensive set of configuration options such as connection timeout and retry. Simply put, the Ribbon lists all the machines behind the Load Balancer in the configuration file. The Ribbon automatically helps you connect these machines based on certain rules (simple polling, random linking, etc.). 2. LB (load balancing) Centralized LB – The use of a separate LB facility (either hardware, such as F5, or software, such as Nginx) between the consumer and provider of the service, which is responsible for forwarding access requests to the provider of the service through certain policies. In-process LB – integrates THE LB logic into the consumer, who learns from the service registry what addresses are available and then selects a suitable server from those addresses. The Ribbon is an in-process LB. It is simply a library that integrates with consumer processes to retrieve service provider addresses. 3. The Ribbon architecture explains that the Ribbon works in two steps: First, it selects EurekaServer. The Ribbon preferentially selects servers with less load in the same region. It then gets an address in the list of service registrations fetched from the server based on user-specified policies. The Ribbon provides several strategies: polling, randomization, and weighting by response time. Ribbon = load balancing + RestTemplate call4. The RestTemplate method returns object for the response data into objects in the body, can be understood as a JSON RestTemplate. GetForObject (); Return objects as ResponseEntity object, contains the response of some important information, such as the response headers, the response status code and response body restTemplate. GetForEntity) (); 5. The core component IRule selects a service to access from the list of services based on a specific algorithm

Com.net flix. Loadbalancer. RoundRobinRule — polling com.net flix. Loadbalancer. RandomRule – random Com.net flix. Loadbalancer. RetryRule – according to the first RoundRobinRule strategies for service, if failed to get the service within a specified time will retry, WeightedResponseTimeRule —- an extension to RoundRobinRule, the faster the response, the heavier the instance selection weight, The more easy to choose BestAvailableRule – will be filtered out due to multiple access failure in the circuit breaker tripped state of service, the minimum amount and then select a concurrent service AvailabilityFilteringRule – to filter out the first example, Select the default rule for instance ZoneAvoidanceRule —-, which has low concurrency, and select the server for the performance of the zone where the Server is located and the availability of the Server

@RibbonClient(Name = "service name ", Configuration = custom Ribbon configuration class)Copy the code
  1. Load balancing algorithm

Number of REST interface requests % Total number of server clusters = Actual server location. The rest interface count starts from 1 after each service restart.

OpenFeign service interface call

  1. An overview of the

Feign is a declarative WebService client that makes it very easy to write Web service clients by creating an interface and adding annotations to the interface.

  1. Feign features 1. Make it easier to write Java Http clients 2. When Ribbon+RestTemplate is used, the RestTemplate encapsulates HTTP requests and forms a set of template invocation methods. However, in real development, because service dependencies may be called in more than one place, often an interface may be called in more than one place, it is common to wrap some client classes for each microservice to wrap the invocation of these dependent services. So, Feign took this one step further and helped us define and implement the definition of the dependent service interface. Under the Feign implementation, we just need to create an interface and configure it with annotations (previously Dao interface with Mapper annotation, now it is a microservice interface with Feign annotation) to complete the interface binding to the service provider. 3. Feign integrates the Ribbon to maintain the service list information of Payment, and implements load balancing on the client through polling. Unlike the Ribbon, Feign provides elegant and simple service invocation in a declarative way by defining the service binding interface.

  2. Difference between Feign and OpenFeign

Feign provides load balancing configuration items

  1. use

Interface + annotation (micro service invocation interface +@FeignClient) add @enableFeignClients to the main startup class and @FeignClient to the business class

  1. OpenFeign timeout control

By default, the Feign client waits only one second, but the server takes more than one second to process, causing the Feign client to return an error. To avoid this, you need to set the Feign client timeout control.

OpenFeign supports the ribbon by default. Ribbon: # Indicates the time taken to establish a connection. 5000 # refers to the time it takes to read the available resource from the server after the connection is established

  1. 1. Overview Feign provides the log printing function. You can adjust the log level through configuration, and monitor and output the calls of Feign interfaces. 2. Log level NONE: The default value is NONE.

BASIC: only request method, URL, response status code and execution time are recorded; HEADERS: Request and response HEADERS in addition to the information defined in BASIC; FULL: In addition to the information defined in HEADRS, there is the body and metadata of the request and response. 3. Yaml needs to enable Feign for logs

Logging: level: # feign log to what level monitoring which interface com. Atguigu. Springcloud. Service. PaymentFeignService: debug

Hystrix circuit breaker

Problems facing distributed systems Replicating applications in a distributed architecture has dozens of dependencies, each of which will inevitably fail at some point.

When A service avalanche calls multiple microservices, it is assumed that microservice A calls microservice B and microservice C, and microservice B and microservice C call other microservices, which is called “fan-out”. If the response time of the invocation of A microservice on the fan-out link is too long or unavailable, the invocation of microservice A will occupy more and more system resources, resulting in system crash, the so-called “avalanche effect”.

For high-traffic applications, a single back-end dependency can cause all resources on all servers to saturate in a matter of seconds. Worse than failure, these applications can cause increased latency between services, strain backup queues, threads, and other system resources, leading to more cascade failures throughout the system. These represent the need to isolate and manage failures and delays so that the failure of a single dependency does not cancel the entire application or system. So, usually when you find that an instance of a module fails, that module still receives traffic, and then that module in question calls other modules, there is a cascading failure, or avalanche.

  1. Hystrix overview

Hystrix is a system to deal with distributed delay, and fault tolerance of the open source library, in a distributed system, many rely on inevitably call fails, such as overtime, abnormal, Hystrix can guarantee in the case of a dependency problem, won’t cause the overall service failure, avoid cascading failure, in order to improve the flexibility of a distributed system. “Circuit breaker” itself is a switching device. When a service unit fails, through the fault monitoring of the circuit breaker (similar to blowing a fuse), an expected and manageable FallBack response is returned to the caller, instead of waiting for a long time or throwing exceptions that the caller cannot handle. This ensures that the threads of service callers are not tied up unnecessarily for long periods of time, preventing failures from spreading and even avalanches in a distributed system.

  1. Hystrix important concepts 1. Service degradation The server is busy, please try again later, do not let the client wait and immediately return a friendly prompt, fallback

What happens when a downgrade occurs? Program running exception 2. Timeout 3. Service fusing triggers service degradation 4. Thread pool/semaphore full degrade configuration: @hystrixCommand 2. Service circuit breaker Overview Circuit breaker is a microservice link protection mechanism against avalanche effect. If a microservice on the fan out link is unavailable or the response time is too long, the service is degraded. In this way, the microservice invocation of the node is interrupted and an incorrect response message is quickly returned. When detecting that the microservice invocation response of this node is normal, the call link is restored. In the Spring Cloud framework, circuit breakers are implemented through Hystrix. Hystrix monitors the status of calls between microservices, and when the number of failed calls reaches a certain threshold, the default is 20 failed calls within five seconds, the circuit breaker is activated. The comment on the circuit breaker mechanism is @hystrixCommand. After the analog fuse reaches the maximum service access, directly deny access, pull the power limit, then call the service degradation method and return a friendly reminder of service degradation -> then fuse -> restore the call link in the main method add: @enablecircuitbreaker # Support for hystrix fuse mechanism 1. The current service will not be called in the fusing open request. The internal clock is generally MTTR (average fault handling time). When the fusing open time reaches the set clock, it enters the semi-fusing state 2. Fuse disable Fuse disable The service is not fused. 3. The fuse is partially open. If the request is successful and meets the rules, the service is restored and the fuse is disabled

There are three important parameters involved in the circuit breaker: snapshot time window, total number of requests threshold, and error percentage threshold. 1: Snapshot time window: The circuit breaker needs to collect request and error data to determine whether to enable the circuit breaker. The snapshot time window is the latest 10 seconds by default.

2: Total request threshold: In the snapshot time window, the number of requests must meet the total request threshold to be eligible for fuse disconnection. The default is 20, which means that if the Hystrix command is invoked less than 20 times within 10 seconds, the circuit breaker will not open even if all requests time out or fail for other reasons.

3: Error percentage threshold: When the total number of requests exceeds the threshold in the snapshot time window, such as 30 calls, if timeout exceptions occur in 15 of the 30 calls, that is, the error percentage exceeds 50%, the breaker will be opened by default at the 50% threshold. Conditions for opening or closing the circuit breaker 1. When a certain threshold is met (more than 20 requests within 10 seconds by default) 2. When the failure rate reaches a certain level (more than 50% of requests fail within 10 seconds by default) 3. At the threshold above, the circuit breaker will open 4. When opened, no requests will be forwarded 5. After a certain amount of time (5 seconds by default), the breaker is half-open and allows one of the requests to be forwarded. If successful, the circuit breaker will close, if not, continue to open. Repeat 4 and 5 after circuit breakers are opened 1: when a request is invoked again, the main logic will not be called, but the degraded fallback will be called directly. Through the circuit breaker, the fault can be found automatically and the degraded logic can be switched to the main logic to reduce the response delay.

2: How to restore the original master logic? Hystrix also provides automatic recovery for this problem. As the circuit breaker opens, to fuse the main logic, hystrix will start a sleep time window, within the time window, relegation logic is temporary into logic, expire when sleep time window, the breaker will enter a state of half open, release a request to the original primary logically, if the request to return to normal, the circuit breaker will continue to be closed, The master logic resumes, and if the request is still in question, the breaker continues to open and the sleep time window restarts. ALL configuration

@HystrixCommand(fallbackMethod = "str_fallbackMethod",
        groupKey = "strGroupCommand",
        commandKey = "strCommand",
        threadPoolKey = "strThreadPool",
​
        commandProperties = {
                // Set the isolation policy, THREAD represents the THREAD pool SEMAPHORE: signal pool isolation
                @HystrixProperty(name = "execution.isolation.strategy".value = "THREAD"),
                // Set the size of the signal pool when the isolation policy is set to signal pool isolation
                @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests".value = "10"),
                // Set the timeout period for command execution
                @HystrixProperty(name = "execution.isolation.thread.timeoutinMilliseconds".value = "10"),
                // Whether to enable timeout
                @HystrixProperty(name = "execution.timeout.enabled".value = "true"),
                // Whether to interrupt execution timeout
                @HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout".value = "true"),
                // Whether execution is interrupted when it is cancelled
                @HystrixProperty(name = "execution.isolation.thread.interruptOnCancel".value = "true"),
                // The maximum number of concurrent callbacks allowed to execute
                @HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests".value = "10"),
                // Whether service degradation is enabled and whether the callback function is executed
                @HystrixProperty(name = "fallback.enabled".value = "true"),
                // Whether to enable the circuit breaker
                @HystrixProperty(name = "circuitBreaker.enabled".value = "true"),
                // This property is used to set the minimum number of requests for a circuit breaker to fuse in a rolling time window. For example, when the default value is 20,
                // If only 19 requests are received within the rolling time window (default: 10 seconds), the breaker will not open even if all 19 requests fail.
                @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold".value = "20"),
                // This property is used to set the number of requests in the scroll window to exceed the number of requests in the scroll window
                / / circuitBreaker requestVolumeThreshold, if errors as a percentage of number of requests for more than 50,
                // Set the circuit breaker to "on", otherwise to "off".
                @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage".value = "50"),
                // This property is used to set the sleep time window after the circuit breaker is turned on. When the sleep time window is over,
                // The circuit breaker will be set to "half open", the request command to fuse the circuit breaker, if still failed to set the circuit breaker to "on",
                // If successful, set the status to "off".
                @HystrixProperty(name = "circuitBreaker.sleepWindowinMilliseconds".value = "5000"),
                // The circuit breaker is forcibly opened
                @HystrixProperty(name = "circuitBreaker.forceOpen".value = "false"),
                // The circuit breaker is forcibly closed
                @HystrixProperty(name = "circuitBreaker.forceClosed".value = "false"),
                // Set the rolling time window. This time is used to collect information for determining the health status of the circuit breaker
                @HystrixProperty(name = "metrics.rollingStats.timeinMilliseconds".value = "10000"),
                // This attribute is used to set the number of buckets to be divided when collecting indicator information in the rolling time window
                // The length of the set time window is divided into multiple "buckets" to accumulate the measurement values, and each "bucket" records the collection indicators in a period of time.
                TimeinMilliseconds must be divisible by numBuckets. Otherwise, an exception will be thrown
                @HystrixProperty(name = "metrics.rollingStats.numBuckets".value = "10"),
                // This property is used to set whether the delay for command execution is tracked and calculated using percentiles. If set to false, all profile statistics will return -1.
                @HystrixProperty(name = "metrics.rollingPercentile.enabled".value = "false"),
                // This property is used to set the duration of the scroll window for percentile statistics in milliseconds.
                @HystrixProperty(name = "metrics.rollingPercentile.timeInMilliseconds".value = "60000"),
                // This property is used to set the number of buckets used in the percentile statistics scroll window.
                @HystrixProperty(name = "metrics.rollingPercentile.numBuckets".value = "60000"),
                // This property is used to set the maximum number of executions reserved for each bucket during execution. If the number of executions exceeding this set point occurs in the rolling time window,
                // Start from the original position. For example, if the value is set to 100 and the scroll window is 10 seconds, if 500 executions occur in a bucket within 10 seconds,
                // Only the last 100 executed statistics are kept in this bucket. In addition, increasing the size of this value increases memory consumption and the computation time required for sorting percentiles.
                @HystrixProperty(name = "metrics.rollingPercentile.bucketSize".value = "100"),
                // This property is used to set the interval to wait for taking health snapshots (success, error percentage of requests) that affect the status of the circuit breaker.
                @HystrixProperty(name = "metrics.healthSnapshot.intervalinMilliseconds".value = "500"),
                // Whether to enable request caching
                @HystrixProperty(name = "requestCache.enabled".value = "true"),
                HystrixCommand specifies whether to print logs of HystrixCommand execution and events to HystrixRequestLog
                @HystrixProperty(name = "requestLog.enabled".value = "true"),
        },
        threadPoolProperties = {
                // This parameter is used to set the number of core threads in the command thread pool. The value is the maximum number of concurrent commands
                @HystrixProperty(name = "coreSize".value = "10"),
                // This parameter sets the maximum queue size of the thread pool. When set to -1, the thread pool uses the queue implemented by SynchronousQueue,
                // Otherwise the queue implemented by LinkedBlockingQueue will be used.
                @HystrixProperty(name = "maxQueueSize".value = "1"),
                // This parameter is used to set the rejection threshold for queues. With this parameter, requests can be rejected even if the queue does not reach its maximum value.
                // This parameter is mainly a complement to the LinkedBlockingQueue queue, because LinkedBlockingQueue
                // The queue cannot dynamically change its object size. This property can be used to adjust the size of the queue that rejects requests.
                @HystrixProperty(name = "queueSizeRejectionThreshold".value = "5"})),Copy the code

3. Service traffic limiting, second killing, high concurrency and other operations, it is strictly prohibited to rush over crowded, everyone queue up, N per second, orderly

3. Workflow

Create HystrixCommand (when a dependent service returns the result of a single operation) or HystrixObserableCommand (when a dependent service returns multiple operation results) objects. 2 Run the command. HystrixComand implements the first two execution modes. HystrixObservableCommand implements the latter two: Execute () : executes synchronously, returning a single result object from a dependent service, or throwing an exception if an error occurs. Queue () : Asynchronous execution, directly returning a Future object containing a single result object to be returned at the end of service execution. Observe () : Returns an Observable that represents the results of an operation and is a Hot Obserable (events are published after being created regardless of whether the “event source” has a “subscriber” or not, So every “subscriber” to a Hot Observable might start halfway through the “event source” and see only part of the operation). ToObservable () : It also returns an Observable that represents multiple results of the operation, but it returns a Cold Observable. (Instead of publishing events when there are no subscribers, it waits until there are subscribers. So for Cold Observable subscribers, it’s guaranteed to see the entire operation from the start. 3 If request caching is enabled and the command cache hits, the cached result is immediately returned as an Observable. 4 Check whether the circuit breaker is on. If the circuit breaker is open, Hystrix does not execute the command, but instead passes to the Fallback processing logic (step 8); If the circuit breaker is off, check if there are resources available to execute the command (step 5). 5 Check whether the thread pool/request queue/semaphore is full. If the command depends on the service’s proprietary thread pool and request queue, or if the semaphore (when thread pools are not used) is already full, Hystrix does not execute the command and instead passes to fallback processing logic (step 8). Hystrix will decide how to request a dependent service based on the method we write. Hystrixcommand-run () : Returns a single result, or throws an exception. HystrixObservableCommand. The construct () : returns a observables object to launch multiple results, or sent via onError error notification. 7 Hystrix reports “success”, “failure”, “rejection”, “timeout” and other information to the circuit breaker, which maintains a set of counters to count these data. The circuit breaker uses these statistics to decide whether to turn the circuit breaker on to “fuse/short-circuit” a service-dependent request. 8 When the command fails to be executed, Hystrix enters the Fallback to try to rollback. This operation is also called “service degradation”. Step 4: The current command is in the “circuit breaker/short circuit” state when the circuit breaker is turned on. Step 5: When the current command’s thread pool, request queue, or semaphore is full. Step 6: HystrixObservableCommand. The construct () or HystrixCommand. The run () throws an exception. 9 When Hystrix is successfully executed, it returns the result directly or as an Observable. Tips: If we do not implement the degrade logic for the command or throw an exception in the degrade processing logic, Hystrix still returns an Observable, but it does not emit any result data. Instead, the onError method tells the command to abort the request immediately. The exception causing the command to fail is sent to the caller through the onError() method.

4. Service monitoring hystrixDashboard

  1. An overview of the

In addition to isolating calls to dependent services, Hystrix also provides quasi-real-time call monitoring (Hystrix Dashboard). Hystrix continuously records the execution information of all requests initiated through Hystrix and presents it to users in the form of statistical reports and graphs. How many requests are executed per second how many successes, how many failures, etc. Netflix monitors these metrics through the Hystrix-metrics-event-stream project. Spring Cloud also provides integration with the Hystrix Dashboard, which translates monitoring content into a visual interface. 2. Hystrix monitoring page

      

Zuul Routing gateway

  1. An overview of the

Zuul is an edge service that provides dynamic routing, monitoring, resiliency, security, and more. Zuul is a Netflix load balancer based on JVM routing and server side. API gateway provides a unified access for services in microservices architecture. Clients access related services through API gateway. The DEFINITION of an API gateway is similar to the facade pattern in design pattern, which is equivalent to the facade in the entire microservices architecture through which all client access is routed and filtered. It realizes the functions of request routing, load balancing, check filtering, service fault tolerance, service aggregation and so on. Zuul contains the most important functions: proxy + routing + filtering

  1. Load balancing

Gateway is the entrance, and the gateway interacts with microservices, so the gateway must realize the function of load balancing. The gateway will obtain the service connection address in the micro-service registry, and then select one of the service addresses with some algorithms to process services. This belongs to the client side of the load balancing, the caller to implement the load balancing logic.

  1. Gray released

At the beginning of gray release, first start a new version of the application, but not directly cut over the flow, but the tester on the new version of the online test, the new version of the application, is our canary. If there are no problems, A small amount of user traffic can be imported to the new version, and then the new version can be observed to collect various runtime data. If various data are compared between the old version and the new version, it is called A/B test. There is no problem with the new version, so gradually expand the scope and traffic, and migrate all users to the new version.

  1. Zuul configuration

Add the following configuration to the main startup class: @enableZuulProxy Enable routing: Zuul mapping configuration + Service name exposed after registration in the registry + REST call address If you do not want to use the default routing rules, you can add the following configuration to ignore the default routing configuration

zuul:
  ignored-services: cloud-provider-payment
  
Enable endpoints for viewing routes
management:
  endpoints:
    web:
      exposure:
        include: 'routes' 
Copy the code
  1. The filter

The filtering function is responsible for the additional processing of the request process and is the basis of request verification filtering and service aggregation. Life cycle:

Filter type:

  • Pre: performs functions such as permission verification and log printing before the request is routed to the target service.

  • Routing: Executed when the request is routed to the destination service

  • Post: After the request is routed to the target service, such as adding header information to the response of the target service, collecting statistics, etc.

  • Error: The request is executed when an error occurs at another stage.

Filter order: The order with the smallest number is executed first

Gateway Indicates the new generation Gateway

  1. An overview of the

One of the most important components in the Cloud bucket is the gateway. In the 1.x version, the Zuul gateway is used. However, in the 2.x version, Zuul’s upgrade was delayed, and SpringCloud finally developed a Gateway to replace Zuul. This is SpringCloud Gateway. Gateway is an API Gateway service built on top of the Spring ecosystem, based on Spring 5, Spring Boot 2, and Project Reactor technologies. Gateway is designed to provide a simple and efficient way to route apis, as well as powerful filter features such as fuses, traffic limiting, retry, and so on. The Reactor-NetTY responsive programming component in Webflux used by SpringCloud Gateway uses netTY communication framework at the bottom.

  1. Microservices gateway location

  1. What does Gateway do?

Reverse proxy authentication Flow control Fusing day monitoring

  1. A Route is the basic building block of a gateway. It consists of an ID, a target URI, a set of assertions, and filters that match the Route if the assertion is true

Predicate developers can match everything in an HTTP request (such as the request header or request parameters) and route the request if it matches the Predicate. Filter refers to an instance of GatewayFilter in the Spring framework, using the Filter, Requests can be modified before or after they are routed.Web request, through some matching criteria, to locate the real service node. And before and after the forwarding process, some fine control. Predicate is our matching condition; Filter, on the other hand, can be interpreted as an omnipotent interceptor. With these two elements, plus the target URI, you can implement a concrete route

  1. Gateway Workflow

Core logic: routing and forwarding + execution filter chain

  1. Gatewey configuration

Gateway Gateway routes can be configured in either of the following modes: 1. Yaml file

 cloud:
    gateway:
      routes:
        - id: payment_routh #payment_route # Specifies the route ID. There is no fixed rule but it must be unique
          uri: http://localhost:8001 # Specifies the route address to provide services
          predicates:
            - Path=/payment/get-id: payment_routh2 #payment_route # route id: payment_routh2 #payment_route http://localhost:8001 # Predicates: -path =/payment/lb/** #Copy the code

2. Inject RouteLocator beans into your code

  1. The use of the Predicate

Overview Spring Cloud Gateway uses route matching as part of the Spring WebFlux HandlerMapping infrastructure. The Spring Cloud Gateway includes a number of built-in Route Predicate factories. All of these predicates match different properties of the HTTP request. The RoutePredicateFactory can be used to create a RoutePredicate object. Predicate objects can be assigned to a Route. The Spring Cloud Gateway contains a number of built-in Route Predicate Factories. All of these predicates match different attributes of the HTTP request. Multiple predicate factories can be combined through logical and. Commonly used Route Predicate

After Route Predicate

Before Route Predicate

Between Route Predicate

Cookie Route Predicate

Header Route Predicate

Host Route Predicate

Method Route Predicate

Path Route Predicate

Query Route Predicate

server:
  port: 9527
​
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true # enable dynamic route creation from registry
      routes:
        - id: payment_routh #payment_route # Specifies the route ID. There is no fixed rule but it must be unique
          # uri: http://localhost:8001 # Route address to provide service after matching
          uri: lb://cloud-payment-service # specifies the routing address of the service to be provided after the match
          predicates:
            - Path=/payment/get-id: payment_routh2 #payment_route # route id: payment_routh2 #payment_route http://localhost:8001 # cloud-payment-service uri: lb://cloud-payment-service predicates: After=2020-02-05T15:10:03.685+08:00[Asia/Shanghai] # Before=2020-02-05T15:10:03.685+08:00[Asia/Shanghai] # 2020-02-02T17:45:06.206+08:00[Asia/Shanghai],2020-03-25T18:59:06.206+08:00[Asia/Shanghai] #- Cookie=username,zzyy #- Header=X-Request-Id, # Host=**. Atguigu.com-method = get-query =username, Eureka: instance: hostname: cloud-gateway-service client: Service provider: register-with-eureka: true fetch-registry: true defaultZone: http://eureka7001.com:7001/eureka # id: our custom routing id, remain the only # # uri: the target service address # # predicates: routing condition, Predicate accept an input parameter returns a Boolean value. This property contains multiple default methods for grouping the Predicate into other complex logic (e.g., and, or, not).Copy the code
  1. The use of the Filter

Overview ROUTING filters can be used to modify incoming HTTP requests and returned HTTP responses. Routing filters can only be used for specified routes. The Spring Cloud Gateway has a variety of routing filters built in, all of which are generated by the GatewayFilter factory class to generate the common GatewayFilter and YAML configurations

AddRequestParameter
​
filters:
      - AddRequestParameter=X-Request-Id,1024 The filter factory will add a pair of headers named x-request-id (1024) to the matching headers
Copy the code

SpringCloud Config Distributed configuration center

Configuration problems for distributed systems Microservices mean that services in a single application are split into sub-services. Each service has a relatively small granularity, so there are a large number of services in the system. Because each service requires the necessary configuration information to operate, a centralized, dynamic configuration management facility is essential.

Config

  1. What is the

SpringCloud Config provides centralized external configuration support for microservices in the microservices architecture, and the configuration server provides a centralized external configuration for all environments of various microservices applications.

  1. How to play

SpringCloud Config is divided into a server and a client. The server, also known as the distributed configuration center, is an independent micro-service application. It connects to the configuration server and provides an access interface for the client to obtain configuration information, encrypt/decrypt information, etc. The client manages application resources and service-related configuration content through the specified configuration center. By default, the configuration server uses Git to store configuration information, which facilitates version management of environment configurations. You can also use git client tools to conveniently manage and access configuration content.

  1. function

Centralized configuration file different environment configuration, dynamic configuration updates, environment to deploy such as dev/test/prod/beta release runtime dynamic adjustment configuration, no longer need to write on each service deployment machine configuration file, When the configuration is changed, the service can sense the configuration change and apply the new configuration to expose the configuration information in the form of REST interfaces

  1. configuration

@enableconFigServer Configures the read rule

/{label}/{application}-{profile}.yml

/{application}-{profile}.yml

/{application}/{profile}[/{label}]

Label: branch

Name: indicates the service name

Profiles: environment (dev/test/prod)

  1. Dynamic refresh

POM introduces actuaor monitoring

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Copy the code

Ymal modified to expose monitoring port

Expose monitor endpoints
management:
  endpoints:
    web:
      exposure:
        include: "*"Add: RefreshScope to the business classCopy the code

SpringCloud Bus Message Bus

Spring Cloud Bus is used in conjunction with Spring Cloud Config to enable dynamic refreshing of configurations.

  1. An overview of the

Spring Cloud Bus is a framework for linking nodes of distributed systems with lightweight messaging systems. It integrates Java’s event handling mechanism with messaging middleware capabilities. Spring Clud Bus currently supports RabbitMQ and Kafka. Bus supports two message brokers: RabbitMQ and Kafka Spring Cloud Bus manages and propagates messages between distributed systems, acting as a distributed actuator for broadcasting state changes, event pushing, etc., and acting as a communication channel between microservices.

  1. The bus

What is the Bus? In microservice architecture systems, lightweight message brokers are often used to build a common message topic and connect all microservice instances in the system. Because messages generated in this topic are listened to and consumed by all instances, it is called a message bus. Each instance on the bus can easily broadcast messages that need to be known to other instances connected to the topic. Basic Principle ConfigClient instances all listen on the same topic in MQ (springCloudBus by default). When a service refreshes data, it puts this information into a Topic so that other services listening on the same Topic can be notified and update their configuration. notice

SpringCloud Stream message driver

  1. concept

Spring Cloud Stream is officially defined as a framework for building message-driven microservices. Applications interact with Binder objects in Spring Cloud Stream through inputs or outputs. Binding is done through our configuration, and The Binder objects of Spring Cloud Stream are responsible for interacting with the messaging middleware. So we just need to figure out how to interact with Spring Cloud Stream to facilitate the message-driven approach. Message event-driven is achieved by using Spring Integration to connect message broker middleware. Spring Cloud Stream provides a personalized automated configuration implementation for some vendors’ message-oriented middleware products, referencing three core concepts of publish-subscribe, consumer group, and partitioning. The unified messaging programming model currently supports only RabbitMQ and Kafka.

  1. Design idea

Standard MQ How messages in a MessageChannel are consumed, Who is responsible for sending and receiving processing – SubscribableChannel, a subinterface of the MessageChannel, is subscribed to by the MessageHandler MessageHandlerWhy Cloud StreamRabbitMQ and Kafka, due to the differences in the architecture of the two message middleware, the differences in the actual development of our project caused some problems. If we use one of the two message queues, I want to migrate to the other message queue. This is a disastrous situation where a lot of stuff has to be pulled down and redone because it’s coupled to our system, and SpringCloud Stream provides us with a way to decouple it.How to unify the underlying differences The separation between the application and the details of the messaging middleware is achieved by defining the Binder as an intermediate layer. Bindings are used to bind producers and consumers of the message container. There are two types of bindings: INPUT and OUTPUT. INPUT corresponds to the consumer, and OUTPUT corresponds to the producer.Message communication in Stream follows the publish-subscribe modelThe Topic is broadcast, which is Exchange in RabbitMQ and Topic in Kakfa.

  1. Standardized process

BinderVery convenient connection middleware, shielding differencesChannelChannel, an abstraction of Queue, is the medium of storage and forwarding in message communication system. The Queue is configured through ChannelThe Source and SinkSimply put, the reference object is the Spring Cloud Stream itself. Publishing messages from the Stream is the output, and receiving messages is the input.4. Common apis and common annotations

SpringCloud Sleuth Distributed request link tracing

In micro service framework, a request by the client in the back-end system will go through a number of different service node calls to collaborate last request as a result, every paragraph request form a complex distributed service call link, link to any part of the high latency or mistakes can cause the failure of the entire request finally.

An overview of the

Spring Cloud Sleuth provides a complete service tracing solution in distributed systems and is compatible with Zipkin support.