Spring Cloud Gateway整合Sentinel流控降级

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

Spring Cloud Gateway整合Sentinel流控降级

pom.xml

        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>

        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-alibaba-sentinel-gatewayartifactId>
        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>springcloudalibabaartifactId>
        <groupId>com.wsm.springcloudgroupId>
        <version>0.0.1-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>gatewayartifactId>

    <dependencies>

        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-gatewayartifactId>
        dependency>

        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>

        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>

        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-alibaba-sentinel-gatewayartifactId>
        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

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级

Spring Cloud Gateway整合Sentinel流控降级
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 handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {

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

                HashMap 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);

    }
}

Spring Cloud Gateway整合Sentinel流控降级
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

Spring Cloud Gateway整合Sentinel流控降级

Original: https://www.cnblogs.com/mingforyou/p/15838995.html
Author: 残星
Title: Spring Cloud Gateway整合Sentinel流控降级

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/540653/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Java常用集合基础概念及源码流程分析

    ArraysList,基于数组实现,默认容量为10,扩容时会先创建一个原始1.5倍的数组,然后再把元素复制过去。特点: 有序,可存重复元素,可存null 查询快,增删慢,适合查询较…

    Java 2023年6月9日
    076
  • (WebFlux)003、多数据源R2dbc事务失效分析

    一、背景 最近项目持续改造,然后把SpringMVC换成了SpringWebflux,然后把Mybatis换成了R2dbc。中间没有遇到什么问题,一切都那么的美滋滋,直到最近一个新…

    Java 2023年6月15日
    080
  • 万字干货|Java基础面试题(2022版)

    作者:小牛呼噜噜 | https://xiaoniuhululu.com计算机内功、JAVA底层、面试相关资料等更多精彩文章在公众号「小牛呼噜噜 」 概念常识 Java 语言有哪些…

    Java 2023年6月15日
    0108
  • 20220808-单例设计模式

    1. 设计模式 2 单例设计模式 2.1 懒汉式 2.2 饿汉式 2.3 区别 1. 设计模式 设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结。 使用…

    Java 2023年6月15日
    088
  • 关于乱码的解决

    创建一个新的项目解决乱码问题 今天在进行一个普通java文件的创建时,发现测试的demo不能输出中文,查看了系统设置之后,是因为系统的编码设置是默认的,为此我们要将编码设置为UTF…

    Java 2023年6月13日
    074
  • springboot集成swagger,出现 No mapping for GET /swagger-ui.html的错误

    在尝试降低springboot版本和swagger版本都无法解决这个问题后 在SpringBoot项目引入Swagger2后,在浏览器地址里输入地址:http://ip:port/…

    Java 2023年5月30日
    065
  • 草图?不管黑猫白猫,能把你的设计理念讲清楚才行

    我在日常工作中,经常要参加一些技术活动,或被拉去参加一些需求会或运营会,时间比较分散。 上周在参加一个代码评审时,发现程序上该复用的没有复用,却写了两份逻辑几乎相同的代码。另外,还…

    Java 2023年6月15日
    094
  • 双亲委派机制

    双亲委派机制 原理 1、一个类加载器接收到类加载请求,它自己并不会先去加载,而是把这个请求委托给父类的加载器去执行 2、如果父类的加载器还有其父类加载器,则进一步向上委托,一次递归…

    Java 2023年6月14日
    079
  • 网络编程(inetAddress类的概述和使用—-UDP发送和接受数据)

    如果一个类没有构造方法: A:成员全部是静态的(Math,Arrays,Collections) B:单例设计模式(Runtime) C:类中有静态方法返回该类的对象(InetAd…

    Java 2023年6月5日
    099
  • docker

    一.Docker入门 1. Docker 为什么会出现 Docker是基于Go语言开发的!开源项目 4.1. 虚拟化技术的缺点 资源占用十分多 冗余步骤多 启动很慢 2.2. 容器…

    Java 2023年6月9日
    0141
  • RabbitMQ实现订单超时案例

    人间清醒 用戶在购买商品的时候通常会预购然后没付款,没付款的订单通常会被设置一个自动超时时间如30分钟后超时,所以我们要在订单到30分钟后自动将超时的订单取消。 DelayQueu…

    Java 2023年6月5日
    085
  • SQL子查询:介绍及分类

    子查询指一个查询语句 嵌套在另一个查询语句内部的查询。 例如:挑选出 员工工资表中, 工资金额比”张三”高的 员工姓名及 工资:d SELECT &…

    Java 2023年6月9日
    076
  • 琐碎的想法(一)代码“优雅”的含义

    优雅的含义 代码优雅曾是翻译而来的,优雅这一个词语源于单词elegant。 elegant有三种含义,优美的(形容举止),精美的(形容物品),简明的。 形容代码上,应该包含了后两种…

    Java 2023年6月8日
    084
  • ELK多租户方案

    一、前言 日志分析是目前重要的系统调试和问题排查的重要手段之一,而目前分布式系统由于实例和机器众多,所以构建一套统一日志系统是非常必要的;ELK提供了一整套解决方案,并且都是开源软…

    Java 2023年6月6日
    0184
  • 枚举.Java学习

    今天复习一下Java里面的 枚举 。 枚举简介 使用enum关键字开发一个枚举类的时候,这个类会默认继承Enum系统类。而且是一个final类。 当多个枚举存在时候。需要逗号分隔,…

    Java 2023年6月9日
    061
  • Mysql安装后打开MySQL Command Line Client闪退的解决方法

    问题原因:安装时mysql command line Client中的my.ini目录地址是MySQL软件的地址!实际上,我们安装MySQL时,一般是MySQL软件地址和MySQL…

    Java 2023年6月5日
    074
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球