coding ++: high concurrent solutions limiting technology - Counters

1. It is the most simple and easiest method of limiting an algorithm

Counter Current Limiting only every 10 minute time of the first request into a request for startTime, startTime + 60s in 10 requests only allow

When more than ten requests within the 60s, rejected, not more than, to reset the time of 60s

Package com.aiyuesheng.utils; 

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

/ ** 
 * @author Chris 
 * @see counter flow restrictor allows only achieved 10 requests per minute of a request into the startTime of time, startTime + 60s in 10 requests only allow 
 * 60s after more than ten when the request, and reject, does not exceed the first 60s to reset the time 
 * / 
@Setter 
@Getter 
public  class LimitService {
     // number of limiting the 
    Private  int maxCount = 10 ;
     // the specified time 
    Private  Long interval the = 60 ;
     // 原子类计数器
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    // 起始时间
    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;
        }
        //Over the time interval, counting starts again directly 
        IF (System.currentTimeMillis () - the startTime> interval The * 1000 ) { 
            the startTime = System.currentTimeMillis (); 
            atomicInteger.set ( . 1 ;)
             return  to true ; 
        } 
        // still time interval , check there is no more than the number of limiting 
        IF (atomicInteger.get ()> maxCount) {
             return  to false ; 
        } 
        return  to true ; 
    } 
}

It is the simplest algorithm, an algorithm easiest flow restrictor, such We require an interface, not requested within one minute more than 10 times, we can set a counter at the start of each request, the counter + 1; If the value of the counter is greater than 10 with the first request and the time interval within 1 minute, then that too many requests, if the request is the first request and the time interval is greater than one minute, and also limits the value of the counter stream within the range, then the counter is reset

 

引文:https://www.cnblogs.com/pickKnow/p/11252120.html

Guess you like

Origin www.cnblogs.com/codingmode/p/11881237.html