Introduction to Soul Chapter 16 rateLimit plugin

introduce

RateLimit is a stream limiting plug-in that allows fine control down to the interface level

The use of rateLimit

1. Enable the rateLimit plug-in in admin and configure the Redis mode and redis address.

2. Add a selector in the rateLimit plug-in page and set rules for the selector, including conditions, bucket capacity, and token rate.

3. The gateway introduces the rateLimit plug-in

 <! -- soul ratelimiter plugin start-->
  <dependency>
      <groupId>org.dromara</groupId>
      <artifactId>soul-spring-boot-starter-plugin-ratelimiter</artifactId>
      <version>${last.version}</version>
  </dependency>
  <! -- soul ratelimiter plugin end-->
Copy the code

4. Restart the gateway

The principle of

RateLimit is implemented through the token bucket. If you get the token, you can access the target resource, otherwise you can return it. Tokens flow into the bucket at a certain rate. RateLimit uses the Redis token bucket.

Here’s a look at the key code for the rateLimit plug-in

@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorData selector, final RuleData rule) {
  // Get the processor name
    final String handle = rule.getHandle();
  // Get the processor
    final RateLimiterHandle limiterHandle = GsonUtils.getInstance().fromJson(handle, RateLimiterHandle.class);
  // Determine whether traffic limiting is required
    return redisRateLimiter.isAllowed(rule.getId(), limiterHandle.getReplenishRate(), limiterHandle.getBurstCapacity())
            .flatMap(response -> {
                if(! response.isAllowed()) { exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); Object error = SoulResultWrap.error(SoulResultEnum.TOO_MANY_REQUESTS.getCode(), SoulResultEnum.TOO_MANY_REQUESTS.getMsg(),null);
                  // Traffic limiting needs to be implemented
                    return WebFluxResultUtils.result(exchange, error);
                }
              // No limit, go down
                return chain.execute(exchange);
            });
}
Copy the code