滑动窗口限流 阿里集群Redis执行lua问题

-ERR bad lua script for redis cluster, all the keys that the script uses should be passed using the KEYS array\r\n

见解释https://help.aliyun.com/document_detail/145968.html?spm=5176.11065259.1996646101.searchclickresult.30071fcfYM8QY7

使用了ratelimitJRRateLimiter rateLimiter = redisson.getRateLimiter(key);....都有报错

限流lua脚本

参考https://github.com/dijia478/redis-cluster-client

 	/**
     * 滑动窗口限流使用的lua脚本,保证原子性
     *
     * local index = tonumber(ARGV[1]);
     * local time_window = tonumber(ARGV[2]);
     * local now_time = tonumber(ARGV[3]);
     * local far_time = redis.call('lindex', KEYS[1] , index);
     * if (not far_time)
     * then
     *   redis.call('lpush', KEYS[1] , now_time);
     *   redis.call('pexpire', KEYS[1] , time_window+1000);
     *   return 1;
     * end
     * if (now_time - far_time > time_window)
     * then
     *   redis.call('rpop', KEYS[1] );
     *   redis.call('lpush', KEYS[1] , now_time);
     *   redis.call('pexpire', KEYS[1] , time_window+1000);
     *   return 1;
     * else
     *   return 0;
     * end
     */
    String SLIDE_WINDOW_LUA = "local index = tonumber(ARGV[1]);\n" + "local time_window = tonumber(ARGV[2]);\n" + "local now_time = tonumber(ARGV[3]);\n" + "local far_time = redis.call('lindex', KEYS[1] , index);\n" + "if (not far_time)\n" + "then\n" + "  redis.call('lpush', KEYS[1] , now_time);\n" + "  redis.call('pexpire', KEYS[1] , time_window+1000);\n" + "  return 1;\n" + "end\n" + "\n" + "if (now_time - far_time > time_window)\n" + "then\n" + "  redis.call('rpop', KEYS[1] );\n" + "  redis.call('lpush', KEYS[1] , now_time);\n" + "  redis.call('pexpire', KEYS[1] , time_window+1000);\n" + "  return 1;\n" + "else\n" + "  return 0;\n" + "end";

 	 /**
     * 是否超过限制
     *
     * @param key        key
     * @param count      次数
     * @param timeWindow 时长 long类型
     * @return 超过限制 false 未超额 true
     */
    public Boolean slideWindowLua(String key, int count, long timeWindow) {
        if (count <= 0 || timeWindow <= 0) {
            return false;
        }
        Object eval = null;
        try {
            List<String> argvList = new ArrayList<>();
            argvList.add(String.valueOf(count - 1));
            argvList.add(String.valueOf(timeWindow));
            argvList.add(String.valueOf(System.currentTimeMillis()));
            eval = jc.eval(SLIDE_WINDOW_LUA, Collections.singletonList(key), argvList);
        } catch (Exception e) {
            log.error("lideWindowLua redis key: {}, count: {}, timeWindow: {}", key, count, timeWindow, e);
        }
        return Long.valueOf(1L).equals(eval);
    }

	//也可以直接使用jedis
	@Autowired
    private JedisCluster jc;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值