We need to limit the number of user visits per unit time according to IP, prevent the swipe of mobile phone verification Code, screen the registration machine, etc., using annotations is very flexible
1 defining annotations
@Retention (retentionpolicy.runtime) @Target (Elementtype.method) @Documented
//highest priority @Order (ordered.highest_precedence) public @interface requestlimit { */ in T count () default Integer.max_value; /**
*/
long time () default 60000< Span style= "color: #000000;" >;}
2 Implementation Notes
@Aspect @component Public classRequestlimitcontract {Private Static FinalLogger Logger = Loggerfactory.getlogger ("Requestlimitlogger");@AutowiredPrivateRedistemplate<string, string>redistemplate; @Before ("Within (@org. Springframework.stereotype.Controller *) && @annotation (limit)") Public voidRequestlimit (FinalJoinpoint joinpoint, requestlimit limit)throwsRequestlimitexception {
Try{object[] args=Joinpoint.getargs (); HttpServletRequest Request=NULL; for(inti = 0; i < args.length; i++) { if(Args[i]instanceofhttpservletrequest) {Request=(HttpServletRequest) args[i]; Break; } } if(Request = =NULL) { Throw NewRequestlimitexception ("Missing httpservletrequest parameter in method"); } String IP=httprequestutil.getipaddr (Request); String URL=Request.getrequesturl (). toString (); String Key= "Req_limit_". Concat (URL). concat (IP); Long Count = Redistemplate.opsforvalue (). Increment (key, 1); if (count = = 1) {Redistemplate.expire (key, Limit.time (), timeunit.milliseconds); } if (Count > Limit.count ()) {logger.info ("User ip[" + IP + "] Access address [" + URL + "] exceeds the number of qualifying times [" + Lim It.count () + "]"); throw new requestlimitexception (); } } Catch(requestlimitexception e) {Throwe; } Catch(Exception e) {logger.error ("Exception occurred:", E); } }}
3 Custom exception
Public class extends Exception { privatestaticfinallong serialversionuid = 1364225358754654702L; Public requestlimitexception () { Super("HTTP request exceeded set limit"); } Public requestlimitexception (String message) { Super(message);} }
4 using in Controller
@RequestLimit (count=100,time=60000)@RequestMapping ("/test") public String Test (HttpServletRequest request, Modelmap modelmap) { //todo }
I used the Redis cache access number and set the self-increment by 1, which is also possible with a static map.
[SPRINGMVC] Custom annotations implement controller access limit