Use ratelimitj to limit the flow of apis.

  java

Order

It is very necessary to carry out flow control for api released to the outside world to prevent malicious attacks so as to protect the system as much as possible. Ratelimitj is a very good open source project and provides an implementation scheme based on redis, hazelcast and inmemory versions. Here is a brief demonstration of how to use the inmemory version.

maven

<!-- https://mvnrepository.com/artifact/es.moki.ratelimitj/ratelimitj-core -->
<dependency>
    <groupId>es.moki.ratelimitj</groupId>
    <artifactId>ratelimitj-core</artifactId>
    <version>0.4.0.M1</version>
</dependency>
<dependency>
  <groupId>es.moki.ratelimitj</groupId>
  <artifactId>ratelimitj-inmemory</artifactId>
  <version>0.4.0.M1</version>
</dependency>

Use

@Component
public class RateLimitService {

    Set<RequestLimitRule> rules = Collections.singleton(RequestLimitRule.of(1, TimeUnit.MINUTES, 50)); // 50 request per minute, per key
    RequestRateLimiter requestRateLimiter = new InMemorySlidingWindowRequestRateLimiter(rules);

    public boolean reached(String key){
        return requestRateLimiter.overLimitWhenIncremented(key);
    }
}

doc