Redis性能提升

文章目录

  • 普通使用
  • 优化使用
  • 性能测试

普通使用

# 定义普通函数
def func():
    """ 以普通方式 操作redis数据库"""
    conn = redis.Redis(host="192.168.0.113", port=6379, db=0, decode_responses=True) #

    # 逐个写入
    conn.set("name1", "jack")
    conn.set("age", 23)
    conn.lpush("friends", "lucy", "lili", "jingtian")
    conn.hset("children", mapping={"name": "zhsan"})

    conn.close()

优化使用

# 定义优化函数
def optimize_func():
    """ 优化后的操作 """
    # 使用连接池 创建连接,避免每次连接的创建、销毁
    conn = Redis(connection_pool=pool, db=0, decode_responses=True)

    # 使用管道 一次性执行命令  (事务>multi开启事务    >exec执行事务   >discard取消事务)
    pipe = conn.pipeline()
    pipe.set("name1", "tom")
    pipe.set("age", 33)
    pipe.lpush("friends", "jeken", "lili", "jingtian")
    pipe.hset("children", mapping={"age": 33})

    # 一次性执行
    pipe.execute()

    pipe.close()
    conn.close()

性能测试

# 性能测试

if __name__ == '__main__':
    timer1 = Timer("func()", "from __main__ import func")
    timer2 = Timer("optimize_func()", "from __main__ import optimize_func")

    # 重复测试五次,每次执行1000次
    r1 = timer1.repeat(5, number=1000)
    r2 = timer2.repeat(5, number=1000)

    print("普通:", r1)
    print("优化:", r2)

普通: [2.7437639, 2.6916931, 2.6703169000000004, 2.674367199999999, 2.7256414999999983]
优化: [0.5129146000000002, 0.5099906000000001, 0.4980922000000003, 0.5055642999999996, 0.5070465000000013]

性能优化约80%
 
 
 
下一篇: Redis发布订阅

你可能感兴趣的:(Redis,redis,数据库,缓存)