Spring Cloud Gateway整合Sentinel流控降級


https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81

 

pom.xml

<!-- sentinel 啟動器 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

        <!-- sentinel 整合 gateway -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
        </dependency>

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloudalibaba</artifactId>
        <groupId>com.wsm.springcloud</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gateway</artifactId>

    <dependencies>
        <!-- gateway的依賴 springcloud開發 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <!-- nacos 服務注冊發現  -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <!-- sentinel 啟動器 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

        <!-- sentinel 整合 gateway -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
        </dependency>

    </dependencies>


</project>

 

application.yml

server:
  port: 8060
spring:
  application:
    name: api-gateway
  cloud:
    # gateway的配置
    gateway:
      # 路由規則
      routes:
        - id: order_route # 路由的唯一標識, 路由到 order
          #          uri: http://localhost:8020 # 需要轉發的地址
          uri: lb://order-nacos-service # 需要轉發的地址  lb:使用nacos中的本地負載均衡策略
          # 斷言規則 用於路由規則的匹配
          predicates:
            - Path=/order-serv/**
              # http://localhost:8060/order-serv/order/add 路由轉到
            # http://localhost:8020/order-serv/order/add
#            - After=2017-01-20T17:42:47.789-07:00[Asia/Shanghai]
#            - Header=X-Request-Id,\d+
#            - Method=GET
#            - Query=name,zhangsan|lisi
#            - CheckAuth=lisi
          filters:
            - StripPrefix=1  # 轉發之前去掉第一層路徑
              # http://localhost:8020/order-serv/order/add 過慮成
            # http://localhost:8020/order/add
#            - AddRequestHeader=X-Request-color, blue
#            - AddRequestParameter=color, red
            - PrefixPath=/mall-order    #添加前綴, 對應微服務需要配置context-path
#            - RedirectTo=302, https://www.baidu.com/ #重定向到百度
#            - SetStatus=404
#            - CheckAuth=lisi
    #跨域配置
#    globalcors:
#      cors-configurations:
#        '[/**]':   # 允許蹃域訪問的資源
##          allowedOrigins: "https://docs.spring.io"   # 跨域允許來源
#          allowedOrigins: "*"   # 跨域允許來源
#          allowedMethods:
#            - GET
#            - POST
    # 配置 Nacos
    nacos:
      server-addr: 127.0.0.1:8848
      discovery:
        #        server-addr: 127.0.0.1:8848
        username: nacos
        password: nacos
        namespace: public
    sentinel:
      transport:
        dashboard: 127.0.0.1:8858

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

package com.wsm.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.HashMap;

@Configuration
public class GatewayConfig {

    @PostConstruct
    public void init() {

        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {

                System.out.println("========="+throwable);

                HashMap<String,String> map = new HashMap();
                map.put("code",HttpStatus.TOO_MANY_REQUESTS.toString());
                map.put("message","限流了");

                //自定義異常處理
                return ServerResponse.status(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(map));
            }
        };

        GatewayCallbackManager.setBlockHandler(blockRequestHandler);

    }
}

 

 

 

server:
  port: 8060
spring:
  application:
    name: api-gateway
  cloud:
    # gateway的配置
    gateway:
      # 路由規則
      routes:
        - id: order_route # 路由的唯一標識, 路由到 order
          #          uri: http://localhost:8020 # 需要轉發的地址
          uri: lb://order-nacos-service # 需要轉發的地址  lb:使用nacos中的本地負載均衡策略
          # 斷言規則 用於路由規則的匹配
          predicates:
            - Path=/order-serv/**
              # http://localhost:8060/order-serv/order/add 路由轉到
            # http://localhost:8020/order-serv/order/add
#            - After=2017-01-20T17:42:47.789-07:00[Asia/Shanghai]
#            - Header=X-Request-Id,\d+
#            - Method=GET
#            - Query=name,zhangsan|lisi
#            - CheckAuth=lisi
          filters:
            - StripPrefix=1  # 轉發之前去掉第一層路徑
              # http://localhost:8020/order-serv/order/add 過慮成
            # http://localhost:8020/order/add
#            - AddRequestHeader=X-Request-color, blue
#            - AddRequestParameter=color, red
            - PrefixPath=/mall-order    #添加前綴, 對應微服務需要配置context-path
#            - RedirectTo=302, https://www.baidu.com/ #重定向到百度
#            - SetStatus=404
#            - CheckAuth=lisi
    #跨域配置
#    globalcors:
#      cors-configurations:
#        '[/**]':   # 允許蹃域訪問的資源
##          allowedOrigins: "https://docs.spring.io"   # 跨域允許來源
#          allowedOrigins: "*"   # 跨域允許來源
#          allowedMethods:
#            - GET
#            - POST
    # 配置 Nacos
    nacos:
      server-addr: 127.0.0.1:8848
      discovery:
        #        server-addr: 127.0.0.1:8848
        username: nacos
        password: nacos
        namespace: public
    sentinel:
      transport:
        dashboard: 127.0.0.1:8858
      scg:
        fallback:
          response-body: "{code:'10001',message:'1001 test'}"
          mode: response

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM