利用redis的monitor监控处理的命令

(1)Shell使用monitor命令监控redis读写记录到文件redis-monitor.txt

#!/bin/bash
cmd=/usr/redis/redis-cli
host=localhost
port=6379
file=redis-monitor.txt
continue_time=$1
   
if [ -z $continue_time ];then
  continue_time=2s
fi
   
echo "$cmd -h $host -p $port monitor run time $(date "+%Y-%m-%d %H:%M:%S") "
`$cmd -h $host -p $port monitor >> $file &`
sleep $continue_time
   
pid=`ps aux | grep "monitor" | grep "redis-cli" | awk '{print $2}'`
echo "will kill redis monitor pid:$pid"
`kill -9 $pid`
echo "redis-cli monitor stopped"

记录文件内容如下:


(2)Python处理统计每秒执行的总数存储到monitor_count.txt

#coding=utf8
#此监控脚本为基于读取到的redis monitor file统计对应的redis操纵况情。
import commands, sys, os, time, string
   
#取time 准确到秒时暂
def getSeconds(time):
    index = time.find(".")
    return time[0:index]
   
#every same seconds ope
class SecondRecords:
    allcount = 0
    #"set:1"
    table = {}
    #init法方为了例实属性与类属性
    def __init__(self, table, count):
        self.table = table
        self.allcount = count
    def get(self):
        return "all count:", self.allcount,"    ",self.table
            
    def add(self, ope):
        if(ope not in self.table.keys()):
            self.table[ope] = 0
        count = self.table[ope]
        count = count + 1
        self.table[ope] = count
        self.allcount = self.allcount + 1;
   
def printResults(results):
    for key in results.keys():
        print key, 't', results[key].get()
   
   
#all monitor records
results = {}
# read monitor file
f = open("redis-monitor.txt")
print("monitor per seconds command processing:")
line = f.readline()
while line:
    strs = line.split(" ")
    #判断否是及格的字符
    length = len(strs)
    #去除非监控指令。
    if(length < 2):
        line = f.readline()
        continue
    time = getSeconds(strs[0])
    if(time not in results.keys()):
        results[time] = SecondRecords({}, 0)
    results[time].add(strs[1])
    line = f.readline()
#close
f.close();
   
results = sorted(results.items(),key=lambda item:item[0])
with open('monitor_count.txt', 'a') as f:
    f.truncate()
    for row in results:
        f.write(row[0] + ':' + str(row[1].allcount)+"n")
    f.close()
   
print ("monitor records saved to file.")

分析后结果如下:

by 雪洁 2018-08-17 08:14:16 675 views
我来说几句

相关文章