五. redis 的簡單操做
#/usr/bin/python
#-*- coding:utf-8 -*-
#@Time :2017/11/26 21:06
#@Auther :liuzhenchuan
#@File :redis 安裝.py
#pycharm 安裝redis 只需導入redis模塊
import redis
##一. redis 簡單操做
#方法一,鏈接redis。及插入數據
redis_config = {
'host':'192.168.16.70',
'port':6379
}
r = redis.Redis(**redis_config)
#set 操做 第一個參數就是key 第二個參數就是value
r.set('liu','you are very good')
# r.keys 就是獲取到全部的keys
print (r.keys())
# r.get 就是獲取到key的值
print r.get('liu')
# 鏈接redis ,方法二
r = redis.Redis(host='192.168.16.70',port=6379)
##二. redis 鏈接池
print '##'*5 + 'redis 鏈接池' + '##'*5
def get_redis_connect():
redis_config = {
'host': '192.168.16.70',
'port': 6379
}
pool = redis.ConnectionPool(**redis_config)
r = redis.Redis(connection_pool=pool)
return r
if __name__ == '__main__':
r = get_redis_connect()
r.set('name','lzc')
r.set('age','18')
print r.get('name')
print r.get('age')
print r.keys()
>>>
##########redis 鏈接池##########
lzc
18
['name', 'liu', 'age']
六. redis 的管道
##能夠一次執行屢次redis 命令
管道:
redis-py 默認在執行每次請求都會建立(鏈接池申請鏈接)和斷開(歸還鏈接池)一次鏈接操做,若是想要在一次請求中指定多個命令,則可使用pipline 實現一次請求指定多個命令,而且默認狀況下一次pipline 是原子性操做。減小功耗redis是一個cs模式的tcp server,使用和http相似的請求響應協議。一個client能夠經過一個socket鏈接發起多個請求命令。每一個請求命令發出後client一般會阻塞
並等待redis 服務處理,redis 處理完成後請求命令後會將結果經過相應報文返回給client。
七. 應用管道與不該用管道的時間差爲10倍
#/usr/bin/python
#-*- coding:utf-8 -*-
#@Time :2017/11/26 23:39
#@Auther :liuzhenchuan
#@File :redis 管道.py
import datetime
import redis
def withpipe(r):
pipe = r.pipeline(transaction=True)
for i in xrange(1, 1000):
key = "test1" + str(i)
value = "test1" + str(i)
pipe.set(key, value)
pipe.execute()
def withoutpipe(r):
# pipe = r.pipeline(transaction=True)
for i in xrange(1, 1000):
key = "test1" + str(i)
value = "test1" + str(i)
r.set(key, value)
if __name__ == "__main__":
pool = redis.ConnectionPool(host="192.168.16.70", port=6379, db=0)
r1 = redis.Redis(connection_pool=pool)
r2 = redis.Redis(connection_pool=pool)
start = datetime.datetime.now()
print(start)
withpipe(r1)
end = datetime.datetime.now()
# print((end-start).microseconds)
print(end-start)
t_time = (end - start).microseconds
print("withpipe time is : {0}".format(t_time))
start = datetime.datetime.now()
withoutpipe(r2)
end = datetime.datetime.now()
t_time = (end - start).microseconds
print("withoutpipe time is : {0}".format(t_time))
>>>
2017-11-26 23:49:58.260000
0:00:00.063000
withpipe time is : 63000
withoutpipe time is : 489000