Using Redis to realize the limit of the number of requests per unit time

PS: Original article, if you need to reprint, please indicate the source, thank you!     

The address of this article: http://flyer0126.iteye.com/blog/2411999

 

Problem requirements:  

The user requests the text message interface restriction rules, and the graphic verification code will be displayed if the request exceeds 3 times within 10 minutes (the graphic verification code needs to be verified before sending the text message).

 

Solutions:

Use Redis List data format;

key:ImageCode_RequestLimit_Uid;

value: request timestamp.

 

Verify implementation:

$key = 'ImageCode_RequestLimit_Uid';
$listLen = lLen($key);
if($listLen < 3){
	// Insert the current timestamp directly into the end of the List
	Lpush($key, now());
} else {
	$index0Time = Lindex($key);
	if((current time - $index0Time) < 10min){
		// Trigger more than 3 requests within 10 minutes, reminding, "Too many requests, please try again later."
		echo "Too many requests, please try again later.";
		exit;
	} else {
		// Insert the current timestamp at the end of the List
		// Get the first element of the List header
		Lpush($key, now());
		Ltrim($key, 0, 2);
	}
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326260360&siteId=291194637