业务需求中经常有需要用到计数器的场景:为了防止恶意刷接口,需要设置一个接口每个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

最新文章

  1. 剑指offer题目61-67
  2. [转载~笔记]CentOS单独编译安装PHP gd库扩展
  3. (转)C语言union(联合体 共用体)
  4. PHP可变长函数方法介绍
  5. 四元数(Quaternion)和旋转
  6. JavaScript之Function函数深入总结
  7. 【转】iOS学习之Autolayout(代码添加约束) -- 不错不错
  8. 使用方便 正则表达式grep,sed,awk(一)
  9. Android的JunitTest
  10. centos快速安装redis
  11. layui框架部分功能介绍
  12. 支付宝sdk集成,报系统繁忙 请稍后再试(ALI64)
  13. PBRT笔记(8)——材质
  14. Android读写配置2
  15. urlconnection代码
  16. win10安装java
  17. FileProvider的使用及应用更新时提示:解析包出错、失败等问题
  18. Java-HashMap、HashSet、hashTable
  19. WordPress Social Warfare组件 远程代码漏洞执行详细复现
  20. 【lintcode13】字符串查找

热门文章

  1. VMware Workstation Pro 14.1.1 正式版
  2. 什么是位、字节、字、KB、MB (转)
  3. 【转】在xcode5中修改整个项目名
  4. PM2 指令简介
  5. [hadoop] hadoop 运行 wordcount
  6. [DQN] What is Deep Reinforcement Learning
  7. 【代码审计】大米CMS_V5.5.3 SQL注入漏洞分析
  8. Fiddler 安装与配置
  9. 关于JSON call 的一个小问题
  10. [原]Jenkins(九)---jenkins分别发布多个项目到多个远程主机