由官方文档而得
python 利用 redis 第三方库
首先安装
pip install redis
然后就可以开始愉快地使用了
import redis
r = redis.StricRedis(host='localhost', port=6379, db=0)
r.set('test', '1')
r.get('test') # ->> '1'
注,r 方法一览:
默认情况下,响应以 Python3 的字节Python 2 的 str 形式返回,用户负责解码操作。
redis-py 实现了两个类来操作 redis
-
StricRedis
尽量坚持官方语法,除了以下命令:-
select
没有实现,考虑到了线程安全 -
del
Python 关键字,用delete
代替 -
config get|se
作为config_get / config_set
实现 -
multi / exec
作为Pipeline
类的一部分实现的。
-
-
Redis
类是StricRedis
的子类,提供向后的兼容性。推荐使用StricRedis
。Redis 覆盖了几个命令:-
lrem
num 和 value 参数顺序颠倒,num 提供默认值 0 -
zadd
Redis类期望* args的形式为:name1,score1,name2,score2,...
,而 StricRedis 是score1,name1,score2,name2,...
,这与 Redis 一样。 -
setex
time 和 value 顺序颠倒。在 Redis 类中是:setex(key, value, time)
,在 StricRedis 类中是:setex(key, time, value)
。
-
连接池来操作
pool = redis.ConnectionPool(host = ' localhost ',port = 6379,db = 0)
r = redis.Redis(connection_pool = pool)
解析器
可以使用 Redis 官方维护的一个 C 库 hiredis
pip install hiredis
线程安全
可以在线程之间安全地共享 Redis 客户端实例。有一点需要注意:Redis SELECT命令。SELECT命令允许您切换连接当前使用的数据库。该数据库保持选定状态直到选择另一个数据库或连接关闭。这会产生一个问题,即连接可以返回到连接到不同数据库的池。因此不会实现 select 命令。
在线程之间传递PubSub或Pipeline对象是不安全的。
管道
一般用来执行事务操作
>>> r = redis.Redis(...)
>>> r.set('bing', 'baz')
>>> # Use the pipeline() method to create a pipeline instance
>>> pipe = r.pipeline()
>>> # The following SET commands are buffered
>>> pipe.set('foo', 'bar')
>>> pipe.get('bing')
>>> # the EXECUTE call sends all buffered commands to the server, returning
>>> # a list of responses, one for each command.
>>> pipe.execute()
[True, 'baz']
也可以进行链式操作
>>> pipe.set(' foo ',' bar ').sadd(' faz ',' baz ').incr(' auto_number ')。execute()
[True,True,6]
禁用原子性:
pipe = r.pipeline(transaction = False)
WATCH 监控命令:
>>> with r.pipeline() as pipe:
... while 1:
... try:
... # 设置一个 watch
... pipe.watch('OUR-SEQUENCE-KEY')
... current_value = pipe.get('OUR-SEQUENCE-KEY')
... next_value = int(current_value) + 1
... # 开始事务
... pipe.multi()
... pipe.set('OUR-SEQUENCE-KEY', next_value)
... # 执行
... pipe.execute()
... # 如果抛出 WatchError ,表示原子性失败
... break
... except WatchError:
... # 另一个客户端修改了,我们必须重试
... continue
由于 Pipeline 在 watch 期间绑定到单个连接,必须调用 reset() 来确保返回连接池,使用 with 上下文的话,它会自动调用。当然也可以手动调用:
>>> pipe = r.pipeline()
>>> while 1:
... try:
... pipe.watch('OUR-SEQUENCE-KEY')
... ...
... pipe.execute()
... break
... except WatchError:
... continue
... finally:
... pipe.reset()
也可以使用 transaction() 方法来简化操作
>>> def client_side_incr(pipe):
... current_value = pipe.get('OUR-SEQUENCE-KEY')
... next_value = int(current_value) + 1
... pipe.multi()
... pipe.set('OUR-SEQUENCE-KEY', next_value)
>>>
>>> r.transaction(client_side_incr, 'OUR-SEQUENCE-KEY')
[True]
注:订阅发布模式还没有详细理解,故没写,以后用到了会写。
迭代器
>>> for key, value in (('A', '1'), ('B', '2'), ('C', '3')):
... r.set(key, value)
>>> for key in r.scan_iter():
... print key, r.get(key)
A 1
B 2
C 3