業務需求中經常有需要用到計數器的場景:為了防止惡意刷接口,需要設置一個接口每個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