python 从mysql获取变为redis获取

葫芦的运维日志

下一篇 搜索 上一篇

浏览量 3903

2019/04/13 12:24


之前做的性能监控 获取后台数据大概有100ms的延迟。

故而想用从redis获取数据替换现有的mysql获取数据方式,看是否能有提升。

因为数据是每分钟采集一次,故redis也是每分钟读取一份最新的数据。

页面展示无论怎样都最大会有1分钟数据延迟,所以改造不会影响展示。

改造拓扑,从左到右:

以网卡io接口改造为例:

1.因采集是每分钟写入一次数据库,故redis每分钟读取一次数据库最新信息,读取脚本如下:

#!/usr/bin/env python
# coding=utf-8
# author: brownwang
# mail: 277215243@qq.com
# datetime:2019/4/13 12:16 AM
# web: https://www.bthlt.com
import MySQLdb
import redis
import json

db = MySQLdb.connect("127.0.0.1", "***", "***", "***", charset='utf8')
cursor = db.cursor()
r = redis.Redis(host='127.0.0.1', port=6379, decode_responses=True)

##  查询接口  ##
def cursorQuery(sql, parlist):
    try:
        cursor.execute(sql, parlist)
    except Exception, e:
        print "Catch exception : " + str(e)
    return cursor.fetchall()


def net_io():
    sql = """select flow_time,add_in,add_out from monitor_net_io order by id desc limit 1440"""
    dataset = cursorQuery(sql, [])
    ret_dic = {}
    ret_dic['add_in'] = []
    ret_dic['add_out'] = []
    ret_dic['flow_time'] = []
    for item in dataset:
        ret_dic['flow_time'].append(str(item[0]).split()[1])
        ret_dic['add_in'].append(int(item[1]) / 60)
        ret_dic['add_out'].append(int(item[2]) / 60)
    for key in ret_dic:
        ret_dic[key].reverse()
    r.hmset('net_io', {'flow_time': json.dumps(ret_dic['flow_time']), 'add_in': json.dumps(ret_dic['add_in']),
                       'add_out': json.dumps(ret_dic['add_out'])})
net_io()

2.前台页面展示从之前的数据库查询,转为从redis获取:

#!/usr/bin/env python
# coding=utf-8
# author: brownwang
# mail: 277215243@qq.com
# datetime:2019/4/13 12:09 AM
# web: https://www.bthlt.com
import redis  # 导入redis模块,通过python操作redis 也可以直接在redis主机的服务端操作缓存数据库
import json
from django.http import JsonResponse

pool = redis.ConnectionPool(host='127.0.0.1', port=6379,
                            decode_responses=True)  # host是redis主机,需要redis服务端和客户端都起着 redis默认端口是6379
r = redis.Redis(connection_pool=pool)


def net_io(request):
    ret_dic = {}
    ret_dic['add_in'] = json.loads(r.hget('net_io', 'add_in'))
    ret_dic['add_out'] = json.loads(r.hget('net_io', 'add_out'))
    ret_dic['flow_time'] = json.loads(r.hget('net_io', 'flow_time'))
    return JsonResponse(ret_dic)

我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=xdbp05fgqmd

葫芦的运维日志

打赏

上一篇 搜索 下一篇
© 冰糖葫芦甜(bthlt.com) 2021 王梓打赏联系方式 陕ICP备17005322号-1