代码之家  ›  专栏  ›  技术社区  ›  Granitosaurus

服务器运行长lua脚本时让redis客户端等待

  •  0
  • Granitosaurus  · 技术社区  · 7 年前

    我有一个redis服务器为多个客户服务。有时服务器需要运行一个lua脚本,该脚本大约需要一分钟才能完成。但在此期间,其他客户端会收到响应错误:

    redis.exceptions.ResponseError:忙碌的redis正忙于运行脚本。您只能调用脚本KILL或SHUTDOWN NOSAVE


    Redis(socket_timeout=9999) 似乎对这个没有影响。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Granitosaurus    7 年前

    我找不到一个合适的方法,所以我做了一点小改动:

    from redis import Redis
    
    class MyRedis(Redis):
        lua_retry_time = 120
    
        # override execute to retry busy errors 
        def execute_command(self, *args, **options):
            wait_time = 0
            if not self.lua_retry_time:
                return super().execute_command(*args, **options)
            while wait_time < self.lua_retry_time:
                try:
                    return super().execute_command(*args, **options)
                except ResponseError as e:
                    if 'busy redis is busy' not in ''.join(e.args).lower():
                        raise e
                    if wait_time == 0:  # only print once
                        print('Redis is busy, waiting up to 120 seconds...')
                    time.sleep(2)
                    wait_time += 2
            return super().execute_command(*args, **options)
    

    每一个命令 redis-py 包裹通过 execute_command 方法这应该涵盖所有内容。