使用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 Wiener * @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
讀后有收獲,小禮物走一走,請作者喝咖啡。
Buy me a coffee. ?Get red packets.作者:樓蘭胡楊
本文版權歸作者和博客園共有,歡迎轉載,但請注明原文鏈接,并保留此段聲明,否則保留追究法律責任的權利。

浙公網安備 33010602011771號