前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 从mysql获取变为redis获取

python 从mysql获取变为redis获取

作者头像
葫芦
发布2019-04-17 16:39:13
3.2K0
发布2019-04-17 16:39:13
举报
文章被收录于专栏:葫芦葫芦

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

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

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

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

改造拓扑,从左到右:

以网卡io接口改造为例:

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

代码语言:javascript
复制
#!/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获取:

代码语言:javascript
复制
#!/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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019/04/13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档