Pyhton之redis操作
1.redis安装
linux系统下安装:
wget http://download.redis.io/releases/redis-3.0.1.tar.gz
tar xzf redis-3.0.1.tar.gz
cd redis-3.0.1
make
vim redis.conf
把daemonize no改为daemonize yes,这样启动时会以守护进程启动
启动redis:
src/./redis-server redis.conf
2.redis简单操作和连接池
#!/usr/bin/env python # -*- coding:utf8 -*- # @Time : 2017/11/24 13:38 # @Author : hantong # @File : redis1.py import redis as redis redis_con = redis.Redis(host="10.3.1.126", port=6379) #连接redis数据库 redis_con.set("shanghai", ' L love you') #redis写入数据 print(redis_con.get("shanghai")) #获取key值为shanghai的values值,并打印 print(redis_con.keys()) #打印所有keys值 #使用连接池操作redis数据库 def redis_config(): re_config = { 'host': '10.3.1.126', 'port': '6379' } pool = redis.ConnectionPool(**re_config) r = redis.Redis(connection_pool=pool) return r if __name__ == "__main__": r = redis_config() r.set("hanson","cool") print(r.get("hanson"))结果:
L love you
['hanson', 'shanghai']
cool
3.redis管道
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2017/10/9 22:45
# @Author : lingxiangxiang
# @File : demon4.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.48.131", 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))
执行结果:withpipe time is : 74000
withoutpipe time is : 814000