基础使用
官方文档
安装
- 同步库
# 主要是json格式的存储
pip install rejson
# 全功能的redis库
pip install redis
- 异步库
pip install aioredis
#or 稳定版
pip install hiredis
# 2022 最新
pip install redis>=4.2.0rc1
引入
from redis import asyncio as aioredis
基础使用
- 一次性链接,每次查询都会重新链接,而链接的消耗比查询的消耗大很多
import aioredis
redis = await aioredis.from_url("redis://localhost", db=1)
redis = await aioredis.from_url("redis://localhost/1")
redis = await aioredis.from_url("redis://user:sEcRet@localhost/")
redis = await aioredis.from_url(
url="redis://localhost", #or host="localhost"
username="user",
password="sEcRet",
encoding="utf-8", # 指定我的输入都是 utf-8 编码
decode_responses=True, # 指定编码,让redis返回已经变吗的数据,默认 utf-8
single_connection_client=True,
)
使用连接池(自动重新连接)
# 创建连接池
使用示例
redis 同步
# 创建连接池
aioredis 异步
async def main():
redis = aioredis.from_url("redis://localhost")
await redis.set("key", "string-value")
bin_value = await redis.get("key")
assert bin_value == b"string-value"
redis = aioredis.from_url("redis://localhost", decode_responses=True)
str_value = await redis.get("key")
assert str_value == "string-value"
await redis.close()
if __name__ == "__main__":
asyncio.run(main())
async def main():
redis = aioredis.from_url("redis://localhost", decode_responses=True)
await redis.hset("hash", mapping={"key1": "value1", "key2": "value2", "key3": 123})
result = await redis.hgetall("hash")
assert result == {
"key1": "value1",
"key2": "value2",
"key3": "123", # note that Redis returns int as string
}
await redis.close()
事务(原子性)
async def main():
redis = await aioredis.from_url("redis://localhost")
async with redis.pipeline(transaction=True) as pipe:
ok1, ok2 = await (
pipe.set("key1", "value1").set("key2", "value2").execute()
)
assert ok1
assert ok2
使用独立链接
async def main():
redis = aioredis.from_url(
"redis://localhost", encoding="utf-8", decode_responses=True
)
async with redis.Client() as connect:
await conn.set("my-key", "value")
val = await conn.get('my-key')
print(val)
# or
async def main_single():
# Create a redis client with only a single connection.
redis = aioredis.Redis(
host="localhost",
encoding="utf-8",
decode_responses=True,
single_connection_client=True,
)
ok = await redis.execute_command("set", "my-key", "some value")
assert ok is True
str_value = await redis.execute_command("get", "my-key")
assert str_value == "some value"
print("str value:", str_value)
# the connection is automatically closed by GC.
使用连接池
async def redis_pool():
# Redis client bound to pool of connections (auto-reconnecting).
redis = aioredis.from_url(
"redis://localhost", encoding="utf-8", decode_responses=True
)
await redis.set("my-key", "value")
val = await redis.get("my-key")
print(val)
注意事项【坑】
链接时间慢
发病环境
- 系统平台:windows10
- redis版本:6.0
临床表现
- 每次链接时间2秒以上,使用set,get,等所以命令的首次使用的过长
- 而且统一个redis,统一系统,采用node的redis模块进行链接则不会发生
相似病例
https://blog.csdn.net/qq_39091354/article/details/111934540
病因分析
这个病因只会在
windows
平台下发生,linux下未测试如果使用
localhost
作为url
给python,python主动请求连接::1这个IP地址,导致了大量的超时和连接失败,最后才会尝试使用127.0.0.1
因为
windows10
下的localhost
实际地址是::1
,是IPv6地址因为一般redis不会在
windows
上使用Pinging DESKTOP-S9VGC7V [::1] with 32 bytes of data:
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
治疗方案
- 不适用
localhost
来用作redis的链接url
扩展阅读
- 什么是
127.0.0.1
- 什么是
localhost
- 什么是
::1
-(0000:0000:0000:0000:0000:0000:0000:0001)