User Interface access time limit using redis, redis times
Assume that a user (determined by IP address) cannot access a service interface more than 10 times per minute.
Import org. apache. commons. lang3.StringUtils; import org. slf4j. logger; import redis. clients. jedis. jedis; import redis. clients. jedis. response; import redis. clients. jedis. transaction;/***** <p> Title: </p> */public class RateLimit {private static final Logger logger = LogUtil. get (); private static final String RATE_LIMIT = "RATELIMIT";/*** @ Title: allow @ Description: Traffic Control, allow access return true not allow access return false * @ param: @ Param key: Enter the redis key. Add the prefix before the key and configure it in eds. redis. prefix * @ param: @ param timeOut time unit: seconds * @ param: @ param count the number of times that access is allowed within the time-out period * @ param: @ param type: * @ param: @ return * @ param: @ throws * Exception @ return: boolean @ throws */public static boolean allow (String type, String key, int timeOut, int count) {// Boolean useFc = Boolean. valueOf (EdsPropertiesUtil. getInstance (). getPr Operty ("flowControl. use"); // returns true if no traffic control is used. // if (! UseFc) {// return true; //} boolean result = false; Jedis jedis = null; StringBuffer keyBuff = new StringBuffer (RATE_LIMIT); keyBuff. append ("_"). append (type ). append (":"). append (key); key = keyBuff. toString (); try {jedis = new Jedis (ConfigurationUtil. getRedisHost (), Integer. valueOf (ConfigurationUtil. getRedisPort (); if (StringUtils. isNoneEmpty (ConfigurationUtil. getRedisPassWord () {jedis. auth (ConfigurationUtil. getRedisPassWord ();} jedis. connect (); Long newTimes = null; Long pttl = jedis. pttl (key); if (pttl> 0) {newTimes = jedis. incr (key); if (newTimes> count) {logger.info ("key :{}, beyond the {} s allowed access limit, this is the {} access ", new Object [] {key, timeOut, count, newTimes}) ;}else {result = true ;}} else if (pttl =-1 | pttl =-2 | pttl = 0) {Transaction tx = jedis. multi (); Response <Long> rsp1 = tx. incr (key); tx. expire (key, timeOut); tx.exe c (); newTimes = rsp1.get (); if (newTimes> count) {logger.info ("key :{}, {} second (s) allowed to access {} times, no. {} Times ", new Object [] {key, timeOut, count, newTimes });} else {result = true;} if (result) {logger. debug ("key :{}, access times {}", new Object [] {key, newTimes}) ;}} catch (Exception e) {logger. error ("Traffic Control exception", e); e. printStackTrace (); // access result = true when an exception occurs;} finally {jedis. close () ;}return result ;}}
ConfigurationUtil is the value in the configuration file.
Method call:
// Limiter, with a maximum of 5 logins within 60 seconds
If (RateLimit. allow ("RECOMMENDCODE", accountCode, 60, 5) {// processing service} else {// return failed}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.