如何使用redis-py模拟python脚本中的redis MONITOR命令?

PIn*_*tag 2 python redis

不幸的是,redis-py库似乎没有Monitor例程.我想阅读redis服务器收到的所有命令,过滤它们,然后记录我感兴趣的命令.有没有人知道如何做到这一点?

Sri*_*nan 8

这是在python中实现监视器代码的一些最小代码.

注意 :

  1. 我从redis-py中的PubSub类改编了这个.请参阅client.py
  2. 这不会解析响应,但这应该足够简单
  3. 不做任何错误处理
import redis        

class Monitor():
    def __init__(self, connection_pool):
        self.connection_pool = connection_pool
        self.connection = None

    def __del__(self):
        try:
            self.reset()
        except:
            pass

    def reset(self):
        if self.connection:
            self.connection_pool.release(self.connection)
            self.connection = None

    def monitor(self):
        if self.connection is None:
            self.connection = self.connection_pool.get_connection(
                'monitor', None)
        self.connection.send_command("monitor")
        return self.listen()

    def parse_response(self):
        return self.connection.read_response()

    def listen(self):
        while True:
            yield self.parse_response()

if  __name__ == '__main__':
    pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
    monitor = Monitor(pool)
    commands = monitor.monitor()

    for c in commands :
        print(c)