Redis使用总结(2):Python接口

安装redis-py

sudo pip2 install redis

牛刀小试

redis连接实例是线程安全的,可以直接将redis连接实例设置为一个全局变量直接使用。如果需要另一个Redis实例(or Redis数据库),需要重新创建redis连接实例来获取一个新的连接。有余这个原因,python的redis接口没有实现select命令。

首先,导入相应的包

import redis

接着,创建连接redis实例

rcon = redis.Redis(host="localhost",port=6379,db=0)

rcon = redis.StrictRedis(host="localhost",port=6379,db=0)

这两者之间的差别可以浏览这个问题

redis-py exposes two client classes that implement these commands
The StrictRedis class attempts to adhere to the official command syntax.
and
In addition to the changes above, the Redis class, a subclass of StrictRedis,
overrides several other commands to provide backwards compatibility with older
versions of redis-py
Do you need backwards compatibility? Use Redis. Don't care? Use StrictRedis.

简单来说就是RedisStrictRedis的子类,用来兼容之前版本的Redis,如果你没有需要兼容的,就用StrictRedis

下面就来尝试一些redis-cli中使用的命令吧

>>> rcon.set('name','Tacey Wong')
True
>>> rcon.get('name')
'Tacey Wong'
>>> rcon['name']
'Tacey Wong'
>>> rcon.keys()
['name']
>>> rcon.dbsize()         #当前数据库中数据条数
1L
>>> rcon.delete('name')
1
>>> rcon.save()               #将数据写回磁盘(保存时阻塞)
True
>>> rcon.get('name');
>>> rcon.flushdb()       #清控rcon实例所选db中的数据
>>> rcon.flushall()        #清空rcon实例中的所有数据(所有db)

Python中使用Redis的管道(pipeline)

管道(pipeline)是redis在提供单个请求中缓冲多条服务器命令的基类子类。通过减少服务器-客户端之间反复的TCP数据库包,从而大大提高了执行批量命令的功能。

创建一个管道

_pipe = rcon.pipeline()

准备多个命令

_pipe.set('hello','redis')
_pipe.sadd('faz','baz')
_pipe.incr('num') 

一次性执行上边的三个命令

>>> _pipe.execute()
[True, 1, 1]

测试读取上边存入的一条数据

>>> rcon.get('hello')
'redis'

管道的命令可以写在一起,如上边的命令可以写成下面的形式:

>>> p.set('hello','redis').sadd('faz','baz').incr('num').execute()
1

默认的情况下,管道里执行的命令可以保证执行的原子性,将transaction设置为False:_pipe = rcon.pipeline(transaction=False)可以禁用这一特性。

后续
参考RedisRedis-cli命令

原文地址:https://www.cnblogs.com/taceywong/p/5843878.html