python3 统计redis中每个DB占用的内存大小

        在一些业务中,会使用多个DB来缓存不同类型的业务数据,有时候redis占用内存过高,造成服务异常。

        redis可以通过dbsize命令来查看当前选择的DB的key的数量,有时候仅仅看key的数量可能还不能直观反映哪块业务数据占用内存多,redis也没有直接的命令可以查询每个DB占用的内存大小。

        这时候通过python开发一个脚本统计每个DB占用的内存大小,可以大致分析是哪些类型业务占用了过高内存。以下是一个统计redis内存并删除占用内存超过10kB的key的样例。

安装python3 redis依赖

pip3 install redis

复制保存为checkRedisMem.py,运行

python3 checkRedisMem.py
# -*- coding: utf-8 -*-
import redis
import random

# Connect to Redis server
r = redis.StrictRedis(host='127.0.0.1', port=6379, password='password')

# Get the number of databases
num_dbs = r.config_get('databases')['databases']

# Iterate over each database
for db_num in range(int(num_dbs)):
    r.select(db_num)  # Select the current database

    # Get all keys in the current database
    keys = r.keys('*')

    # Calculate memory usage for each key and sum them up
    # total_memory = sum(r.memory_usage(key) for key in keys)
    total_memory = 0
    delete_keys = 0
    dbsize = len(keys)
    for key in keys:
        mem = r.memory_usage(key)
        total_memory = total_memory + mem
        # 删除占用内存超过10kB的key
        if mem > 10*1024:
            mem = mem/1024
            delete_keys = delete_keys + 1
            #print(f"DB {db_num} {key}: {mem} kB, delete it!")
            r.delete(key)
        total_memory = total_memory / (1024*1024)
    print(f"DB {db_num}: delete {delete_keys} keys")
    print(f"DB {db_num}: {dbsize} keys, {total_memory} MB")

你可能感兴趣的:(数据库,redis,python)