阿里集群Redis执行lua问题
Posted 伍Wu哈Ha
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了阿里集群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
使用了ratelimitJ
和 RRateLimiter 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;
以上是关于阿里集群Redis执行lua问题的主要内容,如果未能解决你的问题,请参考以下文章