On ----- SpringCloud common components

SpringCloud main role is to manage micro services  

SpringCloud not a specific frame, but a collection of a number of components, assembly springcloud

Include commonly used components are:

  Service registry --Netflix Eureka

  Client load balancing --Netflix Ribbon

  Client load balancing --Feign

  Fuse is --Netflix Hystrix

  Services Gateway --Netflix Gateway (Zuul)

    

 

1, the service registry --Netflix Eureka:

 

Analysis shows:

Eureka is a service registry, only service registration; itself does not provide services nor consumer services. Can build a web project using Eureka, Spring Boot mode can be used to build

Start relies on:

 <dependency>
           <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
 </dependency>

application.yml profile:

server:
  port: 10086
spring:
  application:
    name: eureka-server
eureka:
  client:
    service-url:
      # Eureka service address, if it is a cluster of words; you need to specify other cluster eureka address
      defaultZone: http://127.0.0.1:10086/eureka
    # Do not register themselves
    register-with-eureka: false
    # Does not pull service
    fetch-registry: false

Boot class notes:

 

Service registration and discovery:

EurekaClient registers itself to EurekServer, and get a list of services from EurekaServer remote call
registration services (service provider)
discovery services (caller services)

Discovery notes marked by Eureka client

 

Eureka Server high availability configuration:

Eureka Server is a web application can start multiple instances (configuration different ports) to ensure high availability of Eureka Server

Eureka Server will be registered as a service to other Eureka Server, so that more can be found between Eureka Server at each other, synchronization services, and Eureka Server cluster.

The main configuring a different port;

 

 

2, client load balancing --Netflix Ribbon:

Load balancing is an algorithm can get an address from the address list service call the algorithm implemented by

Ribbon provides polling, two kinds of random load balancing algorithm (default is polling) can be achieved using a service call load balancing algorithm to obtain an address from the address list

Ribbon load balancing achieved by RestTemplate remote call:

In use @LoadBalanced when instantiated RestTemplate the service address can directly use the service name.

 

3, client load balancing --Feign:

Feign major role: The Address Request parameter splicing http.

Feign optimized based on the above encapsulated client load balancing Ribbon, namely: Ribbon + RestTemplate

Implementation steps:

  1. Import initiator relies;

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
  1. Write Feign Feign client @FeignClient open function

// Declare the current class is a Feign client, specify a service called user-service
@FeignClient("user-service")
public interface UserClient {

    //http://user-service/user/123
    @GetMapping("/user/{id}")
    User queryById(@PathVariable Long id);
}

  3, the preparation of a processor ConsumerFeignController, and the use of injection Feign client

@RestController
@RequestMapping("/cf")
public class ComsumerFeignController {

    // remote call by Feign
    @Autowired
    private UserClient userClient;

    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
        return userClient.findById(id);
    }
}

 

4, the fuse is --Netflix Hystrix:

 Action fuse : request a single point of failure can result in the user's service request is blocked, the end result is a thread throughout the service of depleted resources.

 Because dependency services, other services that depend on will lead to the failure of the service is also in a thread is blocked state, eventually leading thread resource depletion until these services are not available,

 Causing the entire system to ask the service is not available, which produce an avalanche effect

Hystrix solve the avalanche effect:

  • Thread isolation: no direct access to the service requested by the user, but the use of thread pool threads to access the service free, accelerated failure time judge.

  • Service degradation: the results of a service call fails to return promptly, so that the thread is not blocked because the wait for service.

Fuse principle:

  

 

By fusing parameters to modify the default configuration of the service:

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 2000
      circuitBreaker:
        errorThresholdPercentage: 50 # fuse triggered the error ratio threshold value, the default value of% 50 
        sleepWindowInMilliseconds: 10000 after long dormancy # fusing, default of 5 seconds
        requestVolumeThreshold: 10 # fusible triggering minimum number request, the default value is 20

 The introduction of coordinates

pom.xml    spring-cloud-starter-netflix-hystrix

Plus bootstrap class   

@SpringCloudApplication
@EnableFeignClients //开启Feign功能
public class ComsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ComsumerApplication.class, args);
    }
Controller class service the caller to provide a method for downgrade
Option One: Write on the method
    @HystrixCommand(fallbackMethod="methodName")
Option Two: downgrade method of extracting out, so use all methods
    Written on the Controller class @DefaultProperties (defaultFallback = "methodName" )
    The Controller approach, @HystrixCommand

Methods downgrade service to be consistent values ​​and parameters and return the original method.

 

Service relationship fuse and service degradation are:

 

closed: the call is the original service (method)
The call is open to downgrade service (method)
half open attempt to invoke existing services, if they can transfer through the blown status to closed, if the transfer fails, or to maintain the open state

 

 

 

5. Service Gateway --Netflix Gateway (Zuul):

The introduction of coordinates

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

Profiles

server:
  port: 10010
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # Route id, arbitrary
        - id: user-service-route
          # Proxy service address
          uri: HTTP: // 127.0.0.1:9091 
          # routing assertion: matches mapped path
          predicates:
            - Path=/user/**
            
# Gateway Gateway address
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    prefer-ip-address: true

Service-Oriented Routing:

Only need to specify the routing path is similar in configuration files; routing services for: lb://user-service

Processing Routing Prefix (filtered):

Address service delivery: http://127.0.0.1:9091/user/8

  • Add the prefix: after adding a prefix as the address and then route the request to the service address of the proxy;

http://127.0.0.1:10010/8 -> http://127.0.0.1:9091/user/8 adding a prefix path / user

  • Prefix removal: After removing some of the request path address prefix as a service path and then the address of the proxy;

http://127.0.0.1:10010/api/user/8 -> http://127.0.0.1:9091/user/8 removed prefix path / api

to sum up:

Service request address micro service address when the client if inconsistent, added and removed can be realized by configuring the route path prefix filter.

 

Note: As the author of Spring Cloud Config and Spring Cloud Bus master is not deep, temporarily Overview

 

Guess you like

Origin www.cnblogs.com/lzh-boke/p/11895870.html