一、安装
redis中操作redis的模块为redis-py
,使用pip install redis
或者easy_install redis
安装即可,也可以进去https://pypi.python.org/pypi/redis
下载源码安装。
二、使用
安装好模块后,使用import redis
即可导入模块。
2.1 创建连接
r = redis.StrictRedis() # 默认连接127.0.0.1:6379
r = redis.StrictRedis(host='127.0.0.1', port=6379, db=0) #显示指定主机、端口号和数据库
2.2 简单命令
# GET/SET
print conn.set("key", "hello") # True
print conn.get("key") # hello
# HGET/HSET 可以使用字典作为参数
print r.hmset('dict', {'aaa': 123, 'bbb': "456"}) # True
print r.hgetall('dict') # {'aaa': '123', 'bbb': '456'}
2.3 事务和管道
WATCH和事务
try:
pipe = conn.pipeline()
pipe.watch('k')
pipe.set('k', '2')
pipe.zadd('zk', 'aaa')
pipe.execute()
except Exception as e:
pipe.unwatch()
print e
管道
管道用法和事务一致,只需要在创建时加上transacton=False
即可:
pipe = conn.pipeline(transacton=False)
其他
事务和管道支持链式调用,即rs = conn.pipeline().set('k', 123).get('k').execute()