五. 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