使用redis堆栈时lua脚本出错

2ledvvac  于 2023-02-28  发布在  Redis
关注(0)|答案(1)|浏览(306)
ReplyError: ERR Error running script (call to f_bda0b62c7548ec7a0d42a3aff20a05872c65d17e): @user_script:1: user_script:1: Attempt to modify a readonly table
    at parseError (/Users/pratham/Documents/cyndia/blog.cyndia.in/frontend/node_modules/.pnpm/redis-parser@3.0.0/node_modules/redis-parser/lib/parser.js:179:12)
    at parseType (/Users/pratham/Documents/cyndia/blog.cyndia.in/frontend/node_modules/.pnpm/redis-parser@3.0.0/node_modules/redis-parser/lib/parser.js:302:14) {
  command: {
    name: 'eval',
    args: [
      'tokens_key = KEYS[1]\n' +
        'local timestamp_key = KEYS[2]\n' +
        '\n' +
        'local rate = tonumber(ARGV[1])\n' +
        'local capacity = tonumber(ARGV[2])\n' +
        'local now = tonumber(ARGV[3])\n' +
        'local requested = tonumber(ARGV[4])\n' +
        '\n' +
        'local fill_time = capacity/rate\n' +
        'local ttl = math.floor(fill_time*2)\n' +
        '\n' +
        'local last_tokens = tonumber(redis.pcall("get", tokens_key))\n' +
        'if last_tokens == nil then\n' +
        '  last_tokens = capacity\n' +
        'end\n' +
        '\n' +
        'local last_refreshed = tonumber(redis.pcall("get", timestamp_key))\n' +
        'if last_refreshed == nil then\n' +
        '  last_refreshed = 0\n' +
        'end\n' +
        '\n' +
        'local delta = math.max(0, now-last_refreshed)\n' +
        'local filled_tokens = math.min(capacity, last_tokens+(delta*rate))\n' +
        'local allowed = filled_tokens >= requested\n' +
        'local new_tokens = filled_tokens\n' +
        'if allowed then\n' +
        '  new_tokens = filled_tokens - requested\n' +
        'end\n' +
        '\n' +
        'redis.pcall("setex", tokens_key, ttl, new_tokens)\n' +
        'redis.pcall("setex", timestamp_key, ttl, now)\n' +
        '\n' +
        'return { allowed, new_tokens }',
      '2',
      '::ffff:127.0.0.1.tokens',
      '::ffff:127.0.0.1.timestamp',
      '100',
      '500',
      '1677125916',
      '1'
    ]
  }
}
oaxa6hgo

oaxa6hgo1#

我发现了一个修复程序,即我没有在第一个变量tokens_key中使用本地变量
所以我只需要在第一个变量中添加local就可以解决这个问题

相关问题