欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringCloud中的路由網(wǎng)關(guān)鑒權(quán)熔斷詳解

 更新時間:2024年01月10日 10:14:36   作者:愛coding的同學(xué)  
這篇文章主要介紹了SpringCloud中的路由網(wǎng)關(guān)鑒權(quán)熔斷詳解,Hystrix是一個用于處理分布式系統(tǒng)的延遲和容錯的開源庫,在分布式系統(tǒng)里,許多依賴不可避免的會調(diào)用失敗,比如超時、異常等,需要的朋友可以參考下

基礎(chǔ)組件

  • 路由網(wǎng)關(guān):GateWay SpringCloud Gateway作為Spring Cloud生態(tài)系統(tǒng)中的網(wǎng)關(guān),目標(biāo)是替代Zuul,在Spring Cloud 2.0以上版本中,沒有對新版本的Zuul 2.0以上最新高性能版本進(jìn)行集成,仍然還是使用的Zuul 1.x非Reactor模式的老版本。而為了提升網(wǎng)關(guān)的性能,SpringCloud Gateway是基于WebFlux框架實(shí)現(xiàn)的,而WebFlux框架底層則使用了高性能的Reactor模式通信框架Netty。Spring Cloud Gateway的目標(biāo)提供統(tǒng)-的路由方式且基于 Filter鏈的方式提供了網(wǎng)關(guān)基本的功能,例如:安全,監(jiān)控/指標(biāo),和限流。
  • 注冊中心:Nacos Nacos 支持基于 DNS 和基于 RPC 的服務(wù)發(fā)現(xiàn)(可以作為springcloud的注冊中心)、動態(tài)配置服務(wù)(可以做配置中心)、動態(tài) DNS 服務(wù)。
  • 負(fù)載均衡:Ribbon 微服務(wù)間的調(diào)用,網(wǎng)關(guān)請求轉(zhuǎn)發(fā),feign都是通過ribbon實(shí)現(xiàn)的,因此學(xué)習(xí)ribbon的原理還是很重要的,而ribbon的作用是用于負(fù)載均衡,springcloud自動化整合配置ribbon是RibbonEurekaAutoConfiguration這個類。對于開發(fā)者來說,使用ribbon只需要在RestTemplate上添加@LoadBalanced注解即可實(shí)現(xiàn)消費(fèi)方的負(fù)載均衡.
  • 熔斷器:Hystrix Hystrix是一個用于處理分布式系統(tǒng)的延遲和容錯的開源庫,在分布式系統(tǒng)里,許多依賴不可避免的會調(diào)用失敗,比如超時、異常等 ,Hystrix 能保證在一個依賴出現(xiàn)問題的情況下,不會導(dǎo)致整體服務(wù)失敗,避免級聯(lián)故障,以提高分布式系統(tǒng)的彈性。 "斷路器"本身是一種開關(guān)裝置,但某個服務(wù)單元發(fā)生故障之后,通過短路器的故障監(jiān)控(類似熔斷保險絲),向調(diào)用方返回一個符合預(yù)期的、可處理的備選響應(yīng)(FallBack),而不是長時間的等待或者拋出調(diào)用方法無法處理的異常,這樣就保證了服務(wù)調(diào)用方的線程不會被長時間、不必要的占用,從而避免了故障在分布式系統(tǒng)中的蔓延,乃至雪崩。

配置

網(wǎng)關(guān) pom.xml 引入:

dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
         <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
</dependencies>

注意 Gateway 默認(rèn)使用的是 webflux,不要引入 web,否則啟動會報錯。

啟動配置 bootstrap.yml,請自行安裝 Nacos:

server:
  port: 8080
spring:
  application:
    name: tools-gateway
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      routes:
      - id: sys
        uri: lb://tools-sys
        predicates:
        - Path=/api/sys/**
        filters:
        - StripPrefix=2
        - name: Hystrix
          args:
            name: fallback
            fallbackUri: forward:/fallback # 熔斷回調(diào)
      - id: weChat
        uri: lb://tools-meizi
        predicates:
        - Path=/api/meizi/**
        filters:
        - StripPrefix=2
    # 跨域請求
    filter:
      remove-hop-by-hop:
        headers:
        - trailer
        - te
        - keep-alive
        - transfer-encoding
        - upgrade
        - proxy-authenticate
        - connection
        - proxy-authorization
        - x-application-context
        - access-control-allow-credentials
        - access-control-allow-headers
        - access-control-allow-methods
        - access-control-allow-origin
        - access-control-max-age
        - vary
      globalcors:
        corsConfigurations:
          '[/**]':
            allowCredentials: true
            allowedHeaders: '*'
            allowedMethods: '*'
            allowedOrigins: '*'
            maxAge: 3628800
# 熔斷
hystrix:
  command:
    default:
      circuitBreaker:
        enabled: true
        errorThresholdPercentage: 50
        forceClosed: false
        forceOpen: false
        requestVolumeThreshold: 4
        sleepWindowInMilliseconds: 10000
      execution:
        isolation:
          semaphore:
            maxConcurrentRequests: 2
          strategy: SEMAPHORE
          thread:
            timeoutInMilliseconds: 3000
      metrics:
        healthSnapshot:
          intervalInMilliseconds: 500
        rollingPercentile:
          bucketSize: 100
          enabled: true
          numBuckets: 6
          timeInMilliseconds: 60000
        rollingStats:
          numBuckets: 10
          timeInMilliseconds: 5000
      requestCache:
        enabled: false
      requestLog:
        enabled: false
  shareSecurityContext: true
  threadpool:
    default:
      coreSize: 1
      maxQueueSize: 200
      queueSizeRejectionThreshold: 2

鑒權(quán)

  /**
         * 判斷 token 是否為空
         */
        if (StringUtils.isBlank(token)) {
            logger.info( "token is empty..." );
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }else{
            /**
             * 驗(yàn)證真?zhèn)?
             */
            CheckResult checkResult = JwtUtils.validateJWT(token);
            if (!checkResult.isSuccess()) {
                logger.info( "token is error..." );
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
        }
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return -100;
    }
    private  static List<String> patterns =
            Arrays.asList(new String[] {"/api/sys/login","/error","/api/sys/v2/api-docs"});
}

熔斷

一般是指軟件系統(tǒng)中,由于某些原因使得服務(wù)出現(xiàn)了過載現(xiàn)象,為防止造成整個系統(tǒng)故障,從而采用的一種保護(hù)措施,所以很多地方把熔斷亦稱為過載保護(hù)。

適用場景

防止應(yīng)用程序直接調(diào)用那些很可能會調(diào)用失敗的遠(yuǎn)程服務(wù)或共享資源。

服務(wù)降級

當(dāng)服務(wù)器壓力劇增的情況下,根據(jù)當(dāng)前業(yè)務(wù)情況及流量對一些服務(wù)和頁面有策略的降級,以此釋放服務(wù)器資源以保證核心任務(wù)的正常運(yùn)行。

核心配置:

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      routes:
      - id: sys
        uri: lb://tools-meizi
        predicates:
        - Path=/api/meizi/**
        filters:
        - StripPrefix=2
        - name: Hystrix
          args:
            name: fallback
            fallbackUri: forward:/fallback # 熔斷回調(diào)

主要參數(shù):

# 熔斷
hystrix:
  command:
    default:
      circuitBreaker:
        enabled: true
        errorThresholdPercentage: 50
        forceClosed: false
        forceOpen: false
        requestVolumeThreshold: 4
        sleepWindowInMilliseconds: 10000
      execution:
        isolation:
          semaphore:
            maxConcurrentRequests: 2
          strategy: SEMAPHORE
          thread:
            timeoutInMilliseconds: 3000
      metrics:
        healthSnapshot:
          intervalInMilliseconds: 500
        rollingPercentile:
          bucketSize: 100
          enabled: true
          numBuckets: 6
          timeInMilliseconds: 60000
        rollingStats:
          numBuckets: 10
          timeInMilliseconds: 5000
      requestCache:
        enabled: false
      requestLog:
        enabled: false
  shareSecurityContext: true
  threadpool:
    default:
      coreSize: 1
      maxQueueSize: 200
      queueSizeRejectionThreshold: 2

核心代碼 DefaultHystrixController

/**
 * 降級處理
 */
@RestController
public class DefaultHystrixController {
    @RequestMapping("/fallback")
    public Map<String,String> fallback(){
        Map<String,String> map = new HashMap<>(8);
        map.put("code","fail");
        map.put("msg","服務(wù)異常");
        return map;
    }
}

小結(jié)

Nacos:Nacos 支持基于 DNS 和基于 RPC 的服務(wù)發(fā)現(xiàn)(可以作為springcloud的注冊中心)、動態(tài)配置服務(wù)(可以做配置中心)、動態(tài) DNS 服務(wù)。

Ribbon:服務(wù)間發(fā)起請求的時候,基于Ribbon做負(fù)載均衡,從一個服務(wù)的多臺機(jī)器中選擇一臺

Hystrix:發(fā)起請求是通過Hystrix的線程池來走的,不同的服務(wù)走不同的線程池,實(shí)現(xiàn)了不同服務(wù)調(diào)用的隔離,避免了服務(wù)雪崩的問題

Gateway:Spring Cloud Gateway的目標(biāo)提供統(tǒng)-的路由方式且基于 Filter鏈的方式提供了網(wǎng)關(guān)基本的功能,例如:安全,監(jiān)控/指標(biāo),和限流。

到此這篇關(guān)于SpringCloud中的路由網(wǎng)關(guān)鑒權(quán)熔斷詳解的文章就介紹到這了,更多相關(guān)SpringCloud路由鑒權(quán)熔斷內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論