一,代码:
"""前台个人资料。"""
from fastapi import APIRouter, Depends, Request
from typing import Annotated
from app.core.deps import get_current_app_user
from app.core.response import success
from app.db.redislink import get_redis_dep
from app.models import AppUserModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.dbsession import get_db
from fastapi import Form
from redis.asyncio import Redis
from app.schemas.profile_schema import UserInfoRequest
router = APIRouter(prefix="/redismonitor", tags=["redis-监控"])
@router.get("/info", summary="个人资料")
async def info(
# user: AppUserModel = Depends(get_current_app_user),
# db: AsyncSession = Depends(get_db),
redis: Redis = Depends(get_redis_dep),
) -> dict:
# 得到info数据
info_data = await redis.info()
# 格式化
list_info = get_format_info(info_data)
list_metrics = get_format_metrics(info_data)
dict_memory = get_format_memory(info_data)
dict_cache = get_format_cache(info_data)
list_core = get_format_core(info_data)
dict = {
"info": list_info,
"metrics":list_metrics,
"memory":dict_memory,
"cache":dict_cache,
"core":list_core,
}
return success(data=dict)
def get_format_info(info) -> list:
list = [
{'name':'redis_version','label':'Redis 版本','value':info['redis_version']},
{'name':'redis_mode','label':'Redis 模式','value':info['redis_mode']},
{'name':'os','label':'操作系统','value':info['os']},
{'name':'arch_bits','label':'架构位数','value':info['arch_bits']},
{'name':'used_memory_human','label':'已用内存','value':info['used_memory_human']},
{'name':'used_memory_peak_human','label':'峰值内存','value':info['used_memory_peak_human']},
{'name':'used_memory_rss_human','label':'物理内存占用','value':info['used_memory_rss_human']},
{'name':'mem_fragmentation_ratio','label':'内存碎片率','value':info['mem_fragmentation_ratio']},
{'name':'mem_allocator','label':'内存分配器','value':info['mem_allocator']},
{'name':'connected_clients','label':'当前连接数','value':info['connected_clients']},
{'name':'total_connections_received','label':'历史连接数','value':info['total_connections_received']},
{'name':'total_commands_processed','label':'总命令数','value':info['total_commands_processed']},
{'name':'instantaneous_ops_per_sec','label':'每秒操作数','value':info['instantaneous_ops_per_sec']},
{'name':'keyspace_hits','label':'命中次数','value':info['keyspace_hits']},
{'name':'keyspace_misses','label':'未命中次数','value':info['keyspace_misses']},
{'name':'expired_keys','label':'淘汰键数','value':info['expired_keys']},
{'name':'evicted_keys','label':'过期键数','value':info['evicted_keys']},
{'name':'rdb_changes_since_last_save','label':'RDB 待写入变更','value':info['rdb_changes_since_last_save']},
{'name':'aof_enabled','label':'AOF 持久化','value':info['aof_enabled']},
{'name':'role','label':'节点角色','value':info['role']},
{'name':'tcp_port','label':'TCP 端口','value':info['tcp_port']},
]
return list
# 一些核心数据
def get_format_core(info) -> list:
list = [
{
'code': 'UP',
'description': str(info['uptime_in_days'])+'天',
'title': '运行时间',
'value': format_time_days(info['uptime_in_seconds']),
},
{
'code': 'CL',
'description': '当前活跃连接',
'title': '连接数',
'value': info['connected_clients'],
},
{
'code': 'MEM',
'description': info['used_memory_human'],
'title': '内存使用',
'value': info['used_memory_human'],
},
{
'code': 'OPS',
'description': '每秒操作数',
'title': 'OPS',
'value': format_number(info['instantaneous_ops_per_sec']),
}
]
return list
def get_format_cache(info) -> dict:
# 得到缓存的命中率
total = info['keyspace_hits']+info['keyspace_misses']
if total == 0:
percentage = 100
else:
percent = (info['keyspace_hits'] / total) * 100
percentage = round(percent, 2)
dict = {
'hitrate': percentage,
'keyspace_hits':info['keyspace_hits'],
'keyspace_misses':info['keyspace_misses'],
'expired_keys':info['expired_keys'],
}
return dict
def get_format_metrics(info) -> list:
instantaneous_ops_per_sec = format_number(info['instantaneous_ops_per_sec'])
instantaneous_input = f"{info['instantaneous_input_kbps']:.2f}" + ' KB/s'
instantaneous_output = f"{info['instantaneous_output_kbps']:.2f}" + ' KB/s'
total_commands_processed = format_number(info['total_commands_processed'])
list = [
{'name':'instantaneous_ops_per_sec','label':'每秒操作','value':instantaneous_ops_per_sec},
{'name':'instantaneous_input','label':'输入流量','value':instantaneous_input},
{'name':'instantaneous_output','label':'输出流量','value':instantaneous_output},
{'name':'total_commands_processed','label':'总命令数','value':total_commands_processed},
]
return list
def get_format_memory(info) -> dict:
# 计算内存的使用比率
max = info['maxmemory']
if max == 0:
max = info['total_system_memory']
percent = (info['used_memory'] / max) * 100
print("percent:",percent)
percentage = round(percent, 2)
print("percentage:",percentage)
dict = {
'percentage': percentage,
"used_memory_human":info['used_memory_human'],
"used_memory_peak_human":info['used_memory_peak_human'],
"used_memory_rss_human":info['used_memory_rss_human'],
"mem_fragmentation_ratio":info['mem_fragmentation_ratio'],
}
return dict
# 格式化数字为字符串
def format_number(number:int) -> str:
if number>1000000:
number_res = number / 1000000
res = f"{number_res:.2f}" + ' M'
return res
elif number>1000:
number_res = number / 1000
res = f"{number_res:.2f}" + ' K'
return res
else:
return str(number)
def format_time_days(seconds: int | float) -> str:
"""
将秒数转换为 'xx天xx小时' 的字符串格式
"""
# 1. 确保秒数不为负数
seconds = max(0, int(seconds))
# 2. 计算天数和剩余的秒数 (1天 = 86400秒)
days, remainder = divmod(seconds, 86400)
# 3. 计算小时数 (1小时 = 3600秒)
hours, _ = divmod(remainder, 3600)
# 4. 返回格式化字符串
return f"{days}天{hours}小时"
二,前端显示效果:
![image]()