Skip to content

redis

redis是 Redis 的 Python 绑定。

安装

Bash
pip install redis

连接 redis

有两种创建连接的方式:

Python
import redis

# 最经典的创建 Redis 的方式
r = redis.Redis(
    host='localhost',
    port=6379,
    db=0,
    password=None
)
    pass

# 通过 url 来实现
r = redis.from_rul("redis://[[username]:[password]]@localhost:6379/0")

运行命令

创建完成 Redis 连接就能够直接运行命令,这些命令和 Redis 的命令是等效的:

Python
import redis

r = redis.Redis(decode_responses=True)
# 对应 SET 命令
r.set('mykey', 'thevalueofmykey')

这其中 decode_responses 非常特殊,默认情况下命令返回的是 bytes,如果指定 decode_responses=True 那么他们会使用 utf-8 来编码他们而返回字符串。

scan 类操作

如果我们需要执行 scan 类操作:

Python
import redis

# 创建 Redis 连接
r = redis.Redis(decode_responses=True)

# 使用 sscan 进行分批迭代
cursor = 0
while True:
    cursor, members = r.sscan("my_key", cursor=cursor)
    for member in members:
        print(member)
    if cursor == 0:
        break  # 当 cursor 为 0 时,表示迭代结束

这个整体比较复杂,如果仅仅想迭代所有的元素,redis-py 还提供了一个 scan-iter() 接口:

Python
import redis

# 创建 Redis 连接
r = redis.Redis(decode_responses=True)

# 使用 sscan_iter 获取一个迭代器
# 这样完全不需要记住游标
for member in r.sscan_iter("my_key"):
    print(member)

批量数据插入

需要注意 redis 中的很多操作并不支持数组,例如 sadd(key, member, member ...) 因此在执行批量插入的时候必须解包数组:

Python
import redis

# 创建 Redis 连接
r = redis.Redis()

# 要批量插入的元素
elements = {"element1", "element2", "element3", "element4"}

# 批量插入数据
# 一定要 *elements 来解包
r.sadd("my_key", *elements)

# 验证插入结果
print(r.smembers("my_key"))

pipeline 和事务

pipeline 是一种优化 Redis 请求的方法,允许你将多个命令打包在一起,一次性的发送给 Redis 服务器,从而减少客户端和服务器之间的通信时间。这在执行大量写操作时尤其有用:

Python
import redis

# 创建 Redis 连接
r = redis.Redis()

# 1. 创建 pipeline 对象
pipe = r.pipeline()

# 2. 批量添加命令到 pipeline 中
pipe.set('key1', 'value1')
pipe.set('key2', 'value2')
pipe.set('key3', 'value3')

# 3. 执行 pipeline 中的所有命令,此时才与服务器进行通信
pipe.execute()

# 也可以链式调用
pipe.set("a", "a value").set("b", "b value").get("a").execute()

pipeline 还可以和事务一起使用,在开启事务的情况下,所有命令要么一起执行要么全部失败:

Python
import redis

# 创建 Redis 连接
r = redis.Redis()

# 使用 pipeline 作为事务
with r.pipeline() as pipe:
    try:
        pipe.multi()  # 开始事务
        pipe.set('key1', 'value1')
        pipe.set('key2', 'value2')
        pipe.set('key3', 'value3')
        pipe.execute()  # 提交事务
    except redis.WatchError:
        print("事务失败,某些数据被修改了")

异步支持

redis-py 提供了异步支持

创建异步连接一个比较特殊的就是他必须显示被关闭:

Python
import redis.asyncio as redis

client = redis.Redis()
print(f"Ping successful: {await client.ping()}")
await client.aclose()

之后允许命令时注意只要涉及与服务器通信的操作都是异步的