簡體   English   中英

如何使用 redis-py 在 python 腳本中模擬 redis MONITOR 命令?

[英]How can I mimic the redis MONITOR command in a python script using redis-py?

不幸的是,redis-py 庫似乎沒有 Monitor 例程。 我想讀取 redis 服務器收到的所有命令,過濾它們,然后記錄我感興趣的那些。有人知道如何做到這一點嗎?

這是在 python 中實現監視器代碼的一些最小代碼。

筆記 :

  1. 我改編自 redis-py 中的 PubSub 類。 見客戶端.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)

現在,redis 庫本身已經包含了監視器支持。 https://github.com/andymccurdy/redis-py/blob/master/redis/client.py#L3422

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM