在SpringCloudGateway中提供了基于令牌桶的限流支持,基于其内置的过滤器工厂RequestRateLimiterGatewayFilterFactory 实现。
在过滤器工厂中是通过Redis和lua脚本结合的方式进行流量控制。
(1)环境搭建<!-- 网关依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!-- eureka网关--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- Lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> <scope>provided</scope> </dependency> <!--redis gateway令牌桶依赖 监控依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--redis gateway令牌桶依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency>
(2)修改application.yml配置文件
server: port: 8001 spring: application: name: server-gateway #服务名称 cloud: gateway: routes: - id: category-service uri: lb://service-category predicates: - Path=/category/**,/admin/category/** filters: #redis令牌桶限流功能 - RewritePath=/admin/category/(?<segment>.*), /admin/category/$\{segment} - name: RequestRateLimiter args: # 使用SpEL从容器中获取对象 key-resolver: '#{@pathKeyResolver}' #当需要用到这里的对象时需要去filter包下的KeyResolverConfiguration类中开启对应的限流bean # 令牌桶每秒填充平均速率 redis-rate-limiter.replenishRate: 1 # 令牌桶的总容量 redis-rate-limiter.burstCapacity: 3 - id: headline-service uri: lb://service-headline predicates: - Path=/headline/**,/admin/headline/** - id: item-service uri: lb://service-item predicates: - Path=/item/**,/admin/item/** - id: user-service uri: lb://service-user predicates: - Path=/user/**,/admin/user/** redis: #当需要用到redis令牌桶限流的时候开启该 port: 6379 host: localhost eureka: client: service-url: defaultZone: http://127.0.0.1:8000/eureka #,http://127.0.0.1:8999/eureka/ registry-fetch-interval-seconds: 5 # 获取服务列表的周期:5s instance: prefer-ip-address: true #使用ip注册 ip-address: 127.0.0.1