Overview of the principle:
The program will determine a time slice. The smaller the time slice, the higher the control accuracy. An access control involves multiple time slices.
When the program requires adding an access record at a certain time, it will first calculate the time slice to be used based on the current time, and add 1 to the counter of this time slice.
When the program determines how many times it has been accessed in a period of time, it will first calculate how many time slices this period contains, then take out all these time slices, add the counter and return.
Principles are introduced here, and program-related source code is here (nodejs)
How to use Redis to build an access frequency control module
Usage example (nodejs):
varredback=require('redback').createClient(),
ratelimit=redback.createRateLimit('requests');
//IncrementthecountforthespecifiedIP
ratelimit.add( '127.0.0.1');
//Countthenumberofrequestsinthelast20seconds
ratelimit.count('127.0.0.1',20,function(err,requests){
if(requests> ;30){
//Throttletheuserinsomeway..
}
});
The above is the detailed content of How to build an access frequency control module with Redis. For more information, please follow other related articles on the PHP Chinese website!