springcloud之gateway限流

 

限流作为网关最基本的功能,Spring Cloud Gateway官方就提供了RequestRateLimiterGatewayFilterFactory这个类,使用Redis和lua脚本实现了令牌桶方式的限流.这个filterFactory依赖RateLimiter及KeyResolver,其中KeyResolver用于从request中提取限流的key,而RateLimiter则是相应的针对key的限流规则.

首先,将这个KeyResolver交由spring管理起来

@Bean(name = "remoteAddrKeyResolver")
    public KeyResolver getKeyResolver() {
        return new KeyResolver() {
            @Override
            public Mono resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
            }
        };
    }

引入redis的依赖,并配置application.yml,这里对consumer-9090实现限流

#端口
server:
  port: 16000
#服务名
spring:
  application:
    name: gateway
  cloud:
    gateway:
      routes: #路由配置:参数为一个List

      - id: consumer-9090 #唯一标识
        uri: lb://RIBBON-CONSUMER #转发的地址,写服务名称
        predicates:
        - Path=/ribbon/** #判断匹配条件,即地址带有/ribbon/**的请求,会转发至lb:RIBBON-CONSUMER
        filters:
        - StripPrefix=1 #去掉Path前缀,参数为1代表去掉/ribbon
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 1  # 填充速度,每秒
            redis-rate-limiter.burstCapacity: 3  # 令牌桶的容积
            key-resolver: "#{@remoteAddrKeyResolver}" #SPEL表达式取的对应的bean

      - id: consumer-9091
        uri: lb://FEIGN-CONSUMER
        predicates:
        - Path=/feign/**
        filters:
        - StripPrefix=1

  redis:
    host: 192.168.183.132
    port: 6379
    password: root
eureka:
  client:
    service-url:
      defaultZone: http://www.aaa.com:10000/eureka,http://www.bbb.com:10001/eureka,http://www.ccc.com:10002/eureka


启动路由工程16000,消费者9090,提供者8080和8081(集群),访问http://localhost:16000/ribbon/helloConsumer并快速刷新,当请求速度超过令牌添加的速度.则请求直接失败.

springcloud之gateway限流_第1张图片

 

你可能感兴趣的:(springcloud)