Current Limiting Technology for High Concurrent Solution--Counter

Keywords: PHP Lombok Java less

1. It is the simplest and easiest current limiting algorithm.

The counter realizes current limiting by allowing only 10 requests per minute for the first request to enter at startTime, and only 10 requests within startTime + 60s.

When there are more than ten requests in 60s, refuse, do not exceed, and reset time in 60s


package com.aiyuesheng.utils;

import java.util.concurrent.atomic.AtomicInteger;
import lombok.Getter;
import lombok.Setter;

/**
 * @author chris
 * @see The counter realizes current limiting by allowing only 10 requests per minute for the first request to enter at startTime, and only 10 requests within startTime + 60s.
 *      When there are more than ten requests in 60s, refuse, do not exceed, and reset time in 60s
 */
@Setter
@Getter
public class LimitService {
    // Number of Current Limits
    private int maxCount = 10;
    // Designated time
    private long interval = 60;
    // Atomic counter
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    // Starting time
    private long startTime = System.currentTimeMillis();

    public boolean limit(int maxCount, int interval) {
        atomicInteger.addAndGet(1);
        if (atomicInteger.get() == 1) {
            startTime = System.currentTimeMillis();
            atomicInteger.addAndGet(1);
            return true;
        }
        // Beyond the interval, start counting directly
        if (System.currentTimeMillis() - startTime > interval * 1000) {
            startTime = System.currentTimeMillis();
            atomicInteger.set(1);
            return true;
        }
        // Still at intervals,check Are there any more than the current limit?
        if (atomicInteger.get() > maxCount) {
            return false;
        }
        return true;
    }
}

 

It is the simplest and easiest algorithm in the current limiting algorithm. For example, we require a certain interface to request no more than 10 times in a minute. We can set a counter at the beginning, each request, the counter + 1. If the value of the counter is greater than 10 and the time interval between the first request and the first request is less than 1 minute, it means that there are too many requests, if the request and the first request are not more than 10 times. If the time interval of a request is more than 1 minute and the value of the counter is within the current limit, reset the counter

Posted by brandye71 on Mon, 14 Oct 2019 10:07:56 -0700