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

 

 

posted @ 2022-01-24 13:08  残星  阅读(898)  评论(0编辑  收藏  举报