Redis管道理解

Redis管道理解

簡介

管道並非Redis自己提供的功能,一般是客戶端提供的功能;web

管道就是打包多條無關命令批量執行,以減小多個命令分別執行消耗的網絡交互時間(TCP網絡交互),能夠顯著提高Redis的性能;redis

管道使用的場景並不適用於,必須知道每次交互結果的場景或者當前的執行依賴於上一次的執行結果等等,相反的,比較適用於對於可靠性不高,容許必定程度的失敗,而且不須要當即獲得執行的反饋,好比羣發短信服務;網絡

須要注意的是,若是以管道處理的形式發送大批的命令,那麼Redis必須將這些命令都執行完存儲在內存中,也就是說,並非批量的命令個數越多越好,不然會形成資源的浪費;ide

操做

# -*- coding: utf-8 -*-

# @Time   : 2019/4/13 5:28 AM
# @Author : George
# @File   : pipeline.py
# @Contact : georgewang1994@163.com

from redis import StrictRedis
import time
conn = StrictRedis()

cache_key_list = ['testing_pipeline_%s' for i in range(10)]
count = 10000
num_list = [num for num in range(count)]

# 遍歷加入
start_time1 = time.time()
for cache_key in cache_key_list:
   for num in num_list:
       conn.sadd(cache_key, num)
end_time1 = time.time()
print u"遍歷加入花費時間: %s's" % (end_time1 - start_time1)

# 命令一次性加入
start_time2 = time.time()
for cache_key in cache_key_list:
   conn.sadd(cache_key, *num_list)
end_time2 = time.time()
print u"命令一次性加入花費時間: %s's" % (end_time2 - start_time2)

# 管道加入
start_time3 = time.time()
pipe = conn.pipeline(transaction=False)
for cache_key in cache_key_list:
   pipe.sadd(cache_key, *num_list)
pipe.execute()
end_time3 = time.time()
print u"管道加入花費時間: %s's" % (end_time3 - start_time3)

# 運行結果
# 遍歷加入花費時間: 11.5690069199's
# 命令一次性加入花費時間: 0.477045059204's
# 管道加入花費時間: 0.41309595108's

原理

todo: 之後補充性能

相關文章
相關標籤/搜索