SpringCloud Alibaba微服务实战十二 - 网关限流

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: SpringCloud Alibaba微服务实战十二 - 网关限流

导读:通过前面的章节我们在微服务层做了限流,并且集成了SpringCloud Gateway,本章主要内容是将限流功能从微服务迁移到网关层。


SpringCloud Gateway 原生限流


Springcloud Gateway 原生限流主要基于过滤器实现,我们可以直接使用内置的过滤器RequestRateLimiterGatewayFilterFactory,目前RequestRateLimiterGatewayFilterFactory的实现依赖于 Redis,所以我们还要引入spring-boot-starter-data-redis-reactive


POM依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifatId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>


限流配置

spring:
  cloud:
    gateway:
      routes:
      - id:account-service
        uri:lb://account-service
        order:10000
        predicates:
        -Path=/account-service/**
        filters:
        - name:RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate:1
            redis-rate-limiter.burstCapacity:3
            key-resolver:"#{@ipKeyResolver}"

主要是配置三个主要参数:

  • redis-rate-limiter.replenishRate :
    允许用户每秒处理多少个请求
  • redis-rate-limiter.burstCapacity :
    令牌桶的容量,允许在一秒钟内完成的最大请求数
  • key-resolver :
    用于限流的键的解析器的 Bean 对象的名字。它使用 SpEL 表达式根据#{@beanName}从 Spring 容器中获取 Bean 对象。

配置Bean

/**
* 自定义限流标志的key,多个维度可以从这里入手
* exchange对象中获取服务ID、请求信息,用户信息等
*/
@Bean
KeyResolver ipKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}


Sentinel 限流


我们之前的章节已经讲过Sentinel的使用方法,如果有不清楚的可以翻看之前的章节,这里主要说一下与SpringCloud gateway的整合。

Sentinel从 1.6.0 版本开始提供了 Spring Cloud Gateway 的适配模块,可以提供两种资源维度的限流:

  • route 维度:即在 Spring 配置文件中配置的路由条目,资源名为对应的 routeId自定义
  • API 维度:用户可以利用 Sentinel 提供的 API 来自定义一些 API 分组

下面是我们的整合步骤


POM依赖

<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
  <groupId>com.alibaba.csp</groupId>
  <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

由于需要使用 nacos作为sentinel的配置中心,所以也引入了sentinel-datasource-nacos


Bootstrap配置

...
spring:
  cloud:
    sentinel:
      transport:
        dashboard:10.0.10.48:8858
      eager:true
      datasource:
        ds:
          nacos:
            server-addr:10.0.10.48:8848
            data-id:gateway-sentinel-flow
            group-id:DEFAULT_GROUP
            rule-type:gw-flow
...

这里主要是sentinel的相关配置,从nacos配置中心获取 gateway-sentinel-flow 配置文件,限流类型是网关类型gw-flow。


限流配置

在nacos配置管理public页面建立 data-idgateway-sentinel-flow 的配置文件(json格式),给account-serviceproduct-service添加限流规则。

[
  {
    "resource": "account-service",
    "count": 5,
    "grade": 1,
    "paramItem": {
        "parseStrategy": 0
    }
  },
  {
    "resource": "product-service",
    "count": 2,
    "grade": 1,
    "paramItem": {
        "parseStrategy": 0
    }
  }
]

配置完成以后启动网关项目,登录sentinel控制台,查看限流规则:

配置说明:

以客户端IP作为限流因子
public static final int PARAM_PARSE_STRATEGY_CLIENT_IP = 0;
以客户端HOST作为限流因子
public static final int PARAM_PARSE_STRATEGY_HOST = 1;
以客户端HEADER参数作为限流因子
public static final int PARAM_PARSE_STRATEGY_HEADER = 2;
以客户端请求参数作为限流因子
public static final int PARAM_PARSE_STRATEGY_URL_PARAM = 3;
以客户端请求Cookie作为限流因子
public static final int PARAM_PARSE_STRATEGY_COOKIE = 4;


限流测试

多次通过网关访问account-service服务进行测试 http://localhost:8090/account/getByCode/javadaily 查看限流效果:


自定义响应异常

SpringCloud-gateway限流异常默认的实现逻辑为SentinelGatewayBlockExceptionHandler,可以查看源码发现异常响应的关键代码如下

由于服务后端都是返回JSON的响应格式,所以我们需要修改原异常响应,将其修改成ResultData类的响应格式。要实现这个功能只需要写个新的异常处理器然后在SpringCloud GateWay配置类中注入新的异常处理器即可。

  • 自定义异常处理器CustomGatewayBlockExceptionHandler
publicclass CustomGatewayBlockExceptionHandler implements WebExceptionHandler {
  ...
    /**
     * 重写限流响应,改造成JSON格式的响应数据
     * @author javadaily
     * @date 2020/1/20 15:03
     */
    private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) {
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        ResultData<Object> resultData = ResultData.fail(ReturnCode.RC200.getCode(), ReturnCode.RC200.getMessage());
        String resultString = JSON.toJSONString(resultData);
        DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(resultString.getBytes());
        return serverHttpResponse.writeWith(Mono.just(buffer));
    }
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        } else {
            return !BlockException.isBlockException(ex) ? Mono.error(ex) : this.handleBlockedRequest(exchange, ex).flatMap((response) -> this.writeResponse(response, exchange));
        }
    }
   ...
}

大家可以直接复制 SentinelGatewayBlockExceptionHandler 类,然后修改 writeResponse方法接口

  • 修改Gateway配置类,注入CustomGatewayBlockExceptionHandler
@Configuration
publicclass GatewayConfiguration {
  ...
    /**
     * 注入自定义网关异常
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public CustomGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        // Register the custom block exception handler .
        returnnew CustomGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }
  ...
}
  • 在bootstrap.yml文件中新增配置
spring:
  main:
    allow-bean-definition-overriding:true
  • 重新测试,限流响应结果如下
{
  "message": "服务开启限流保护,请稍后再试!",
  "status": 200,
  "success": false,
  "timestamp": 1579509123946
}


限流不生效

各位在使用过程中如果发现网关层限流不生效,可以以debug模式启动网关服务,然后对网关过滤器 SentinelGatewayFilter 中的filter方法进行调试,我发现sentinel获取到的网关id并不是我们配置的account-service,而是加了CompositeDiscoveryClient_前缀,如下图所示:

所以我们需要修改 gateway-sentinel-flow  的配置,给我们的resource 也加上前缀,修改完的配置如下:

[{
  "resource": "CompositeDiscoveryClient_account-service",
  "count": 5,
  "grade": 1,
  "paramItem": {
    "parseStrategy": 0
  }
}, {
  "resource": "CompositeDiscoveryClient_product-service",
  "count": 2,
  "grade": 1,
  "paramItem": {
    "parseStrategy": 0
  }
}]

通过使用jemter对接口进行测试,发现网关能正常限流

经过以上几步,我们可以将后端微服务层的限流配置去掉,让网关层承担限流的功能。

好了,各位朋友们,本期的内容到此就全部结束啦,能看到这里的同学都是优秀的同学,下一个升职加薪的就是你了!

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
18天前
|
算法 NoSQL API
SpringCloud&Gateway网关限流
SpringCloud&Gateway网关限流
40 7
|
4天前
|
负载均衡 Java 网络架构
在SpringCloud2023中快速集成SpringCloudGateway网关
本文主要简单介绍SpringCloud2023实战中SpringCoudGateway的搭建。后续的文章将会介绍在微服务中使用熔断Sentinel、鉴权OAuth2、SSO等技术。
29 2
在SpringCloud2023中快速集成SpringCloudGateway网关
|
15天前
|
Cloud Native Java Nacos
Spring Cloud Nacos:概念与实战应用
【4月更文挑战第28天】Spring Cloud Nacos 是一个基于 Spring Cloud 构建的服务发现和配置管理工具,适用于微服务架构。Nacos 提供了动态服务发现、服务配置、服务元数据及流量管理等功能,帮助开发者构建云原生应用。
21 0
|
19天前
|
Java API Nacos
第十二章 Spring Cloud Alibaba Sentinel
第十二章 Spring Cloud Alibaba Sentinel
27 0
|
19天前
|
存储 前端开发 Java
第十一章 Spring Cloud Alibaba nacos配置中心
第十一章 Spring Cloud Alibaba nacos配置中心
25 0
|
19天前
|
消息中间件 SpringCloudAlibaba Java
第十章 SpringCloud Alibaba 之 Nacos discovery
第十章 SpringCloud Alibaba 之 Nacos discovery
|
19天前
|
Java Nacos 开发者
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
|
2月前
|
运维 网络协议 安全
长连接网关技术专题(十):百度基于Go的千万级统一长连接服务架构实践
本文将介绍百度基于golang实现的统一长连接服务,从统一长连接功能实现和性能优化等角度,描述了其在设计、开发和维护过程中面临的问题和挑战,并重点介绍了解决相关问题和挑战的方案和实践经验。
112 1
|
6月前
|
负载均衡 应用服务中间件 API
微服务技术系列教程(25) - SpringCloud- 接口网关服务Zuul
微服务技术系列教程(25) - SpringCloud- 接口网关服务Zuul
61 0
|
5月前
|
负载均衡 Cloud Native Java
【云原生】Spring Cloud Alibaba 之 Gateway 服务网关实战开发
【云原生】Spring Cloud Alibaba 之 Gateway 服务网关实战开发
473 0