Last active
September 25, 2015 06:58
-
-
Save nmische/881766 to your computer and use it in GitHub Desktop.
Simple time based limiter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!--- set up app ---> | |
<cfapplication name="ratelimit"/> | |
<cfif not StructKeyExists(application,"limiter") or StructKeyExists(url,"reset")> | |
<cfset application.limiter = CreateObject("component","TimeBasedRateLimiter")/> | |
</cfif> | |
<!--- check our limiter ---> | |
<cfif application.limiter.requestsRemaining() gt 0> | |
<cfset application.limiter.push() /> | |
<p>Request was successful.</p> | |
<cfelse> | |
<p>Request was not successful.</p> | |
</cfif> | |
<!--- show how many requests we have left ---> | |
<cfoutput> | |
<p>You have #application.limiter.requestsRemaining()# requests remaining.</p> | |
</cfoutput> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
component { | |
variables.stack = []; | |
variables.requestLimit = 100; | |
variables.timeLimitInSeconds = 60; | |
public function push() { | |
lock name="timeBasedRateLimiter" type="exclusive" timeout="30" { | |
ArrayAppend(variables.stack,Now()); | |
} | |
} | |
public function requestsRemaining() { | |
return variables.requestLimit - size(); | |
} | |
private function size() { | |
lock name="timeBasedRateLimiter" type="exclusive" timeout="30" { | |
while ((ArrayLen(variables.stack) gt 0) and (DateDiff('s',variables.stack[1],Now()) gt variables.timeLimitInSeconds)) { | |
ArrayDeleteAt(variables.stack,1); | |
} | |
} | |
return ArrayLen(variables.stack); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment