做法

使用redis的lua脚本功能来限频

在redis中定时刷新系统时间来作为一个全局的时钟

限频脚本:

	/**
* 获取令牌的lua脚本
*/
public final static String SCRIPT = "local epoch = redis.call(\"hget\",KEYS[1],'Epoch');\n" +
"local currentEpoch = tonumber(ARGV[1]);\n" +
"if(epoch == false and currentEpoch ~= epoch) then\n" +
" redis.call('hset', KEYS[1], 'Epoch',currentEpoch);\n" +
" redis.call(\"hset\", KEYS[1], 'Count', tonumber(ARGV[2]));\n" +
" redis.call('pexpire', KEYS[1], 2000);\n" +
" return 1;\n" +
"end; \n" +
"local currentCount = redis.call(\"HINCRBY\", KEYS[1],'Count', tonumber(ARGV[3]));\n" +
"if(currentCount > 0) then \n" +
" return 1;\n" +
"else \n" +
" return 2;\n" +
"end;"; /**
* 同步系统时间到redis 中的lua脚本
*/
public final static String SET_SYSTEM_TIME_SCRIPT = "local clientId = redis.call(\"hget\",KEYS[1],'Client'); \n" +
"if (clientId == false or clientId == ARGV[1]) then \n" +
" redis.call('hset', KEYS[1], 'Client', ARGV[1]);\n" +
" redis.call('hset', KEYS[1], 'Time' ,ARGV[2]);\n" +
" redis.call('pexpire', KEYS[1], tonumber(ARGV[3]));\n" +
" return 1;\n" +
"end;\n" +
"return 2;";

java调用代码:

  List<String> keys = new ArrayList<String>();
keys.add("JRateLimit-Key-" + source); List<String> args = new ArrayList<String>();
args.add(currentEpoch + ""); //currentEpoch是通过获取全局时钟来做的
args.add(permitsPerEpoch + "");
args.add((0 - permits) + ""); Object result = client.evalsha(LIMIT_LUA_SCRIPT_SHA, keys, args, false); //result的类型即为lua脚本中的返回值类型,Long

策略

通过redis实现全局时钟

通过一次多取几个令牌放到内存中来解决超大调用频率导致的redis请求单机ops极限问题

最新文章

  1. SmartUpLoad自动上传包
  2. 新买了ipad,在ipad上面看见的一个效果,pc上应该也见过,但是还是ipad上面有印象,如果是弹性运动就最好了
  3. 源码解读—LinkedList
  4. 第三章 设计程序架构 之 设计实现Windows Azure 角色生命周期
  5. 【算法题】- 求和等于K子数组
  6. 省选训练赛第4场D题(多米诺骨牌)
  7. 关于 addEventListener 和 handleEvent 方法
  8. uva 11636 Hello World!
  9. SSM-MyBatis-04:Mybatis中使用properties整合jdbc.properties
  10. 测试修改hosts文件py小工具
  11. 深度学习之卷积神经网络(CNN)详解与代码实现(二)
  12. HDU 1228(字符串处理)
  13. 【AtCoder】ARC073
  14. TensorFlow模型加载与保存
  15. Python--详解Python中re.sub
  16. 谈谈 在 .Net 生态里为什么没有 Hadoop 系列 ?
  17. java 图片的自定义大小
  18. UVaLive 3357 Pinary (Fib数列+递归)
  19. node爬虫(转)
  20. CSUOJ 1341 String and Arrays

热门文章

  1. Python爬虫和函数调试
  2. 关于bat中日期时间字符串的格式化
  3. Spring Cloud各组件学习
  4. dubbo学习(二)配置dubbo XML方式配置
  5. Spring学习(十)Spring知识点汇总
  6. Artwork (Gym - 102346A)【DFS、连通块】
  7. Dledger的是如何实现主从自动切换的
  8. 靠这些秋招秘笈,齐姐的学妹今年已经拿到了 8 个offer!
  9. Excel双击“单元格”后,自动跳转到相关“工作表
  10. 077 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 02 类和对象