使用Redis 計數器防止刷接口


        業務需求中經常有需要用到計數器的場景:為了防止惡意刷接口,需要設置一個接口每個IP一分鍾、一天等的調用次數閾值;為了降低費用,限制發送短信的次數等。使用Redis的Incr自增命令可以輕松實現以上需求,而且避免驗證碼帶來的弊端,如不夠人性化,用戶操作時間長、體驗差等。以一個接口每個IP每分鍾限制調用100次為例:

    private boolean isDenied(String ip){

         SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDHHmm");
         String time = sdf.format(Calendar.getInstance().getTime());

         long count=JedisUtil.setIncr(time +"_"+ip+"_IP", 86400);

 if(count<=100){ return false; } return true; }
public class JedisUtil {
    protected final static Logger logger = Logger.getLogger(JedisUtil.class);
    private static  JedisPool jedisPool;
    
    @Autowired(required = true)
    public void setJedisPool(JedisPool jedisPool) {
        JedisUtil.jedisPool = jedisPool;
    }
    /**
     * 對某個鍵的值自增
     * @author liboyi
     * @param key 鍵
     * @param cacheSeconds 超時時間,0為不超時
     * @return
     */
    public static long setIncr(String key, int cacheSeconds) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result =jedis.incr(key);
            if (cacheSeconds != 0) {
             jedis.expire(key, cacheSeconds);
            }
            logger.debug("set "+ key + " = " + result);
        } catch (Exception e) {
            logger.warn("set "+ key + " = " + result);
        } finally {
            jedisPool.returnResource(jedis);
        }
        return result;
    }
}    

參考文獻:https://blog.csdn.net/qq_33556185/article/details/79427271


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM