持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第21天,点击查看活动详情

asyncio (3156) Redis 客户端库。该库旨在为基于 asyncio 的 Redis 提供简单明了的接口。

前言:

今天来介绍一款非常适用于Fastapi的连接redis的客户端攻击,因为fastapi的优秀异步能力,不得不给他也配一个支持异步的连接redis工具,那么,aioredis 他来了。

本文章主要介绍aioredis的快速简单用法。意于抛砖引玉,不会对于具体api进行详细的说明,需要一定的使用redis-py的经验。

基础环境:

首先准备如下基础环境:

  • aioredis (version>=2.0)
  • python环境为3.9

要注意一下 在2.0版本已经不需要用舍弃了create_redis_pool的连接方式,整个核心和公共API已经经过重构,完美拥抱redis-py,所以此文章不在讲述低于2.0版本的功能和用法。

连接方式:

import asyncio
import aioredis


async def main():
    # Redis client bound to single connection (no auto reconnection).
    redis = aioredis.from_url(
        redis://127.0.0.1", port=44117, password='qwaszx', db=2, encoding="utf-8", decode_responses=True
    )
    
    async with redis.client() as conn:
        await conn.set("my-key", "value")
        val = await conn.get("my-key")
        print(val)
        
        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)
            
            if __name__ == "__main__":
                asyncio.run(main())
    asyncio.run(redis_pool())
复制代码

在Fastapi中使用实例:

在项目创建时将redis挂载到app上

from fastapi import FastAPI

def register_redis(app: FastAPI):
    async def redis_pool():
        redis = await aioredis.from_url(
        url="redis://127.0.0.1", port=44117, password='qwaszx', db=2, encoding="utf-8", decode_responses=True
    )
        return redis
        
    @app.on_event("startup")
    async def srartup_event():
        app.state.redis = await redis_pool()
        
 from fastapi import FastAPI

app = FastAPI()
# 进行挂载
register_redis(app)


@app.get("/test")
async def test(q: str):
    key = time.time()
    await app.state.redis.set(key=key, value=q)
    # 添加数据,5秒后自动清除
    await app.state.redis.setex(key="vvv", seconds=5, value="临时存在")
    value = await app.state.redis.get(key=key)
    return {key: value}
复制代码

子路由中使用:

  • 添加参数request: Request
  • 通过request.app.state.redis获取Redis实例
  • 通过获取到的实例,进行操作Redis
router = APIRouter()

@router.get("/api/test")
async def test(request: Request, value: str):
    api_time = f"api-{time.time()}"
    await request.app.state.redis.setex(key=api_time, seconds=5.5, value=value)
    value = await request.app.state.redis.get(key=api_time)
    return {api_time: value}

app.include_router(router)

作者:rational
链接:https://juejin.cn/post/7109815559730462727
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted on 2022-11-25 15:16  专注于区块链开发  阅读(1895)  评论(0编辑  收藏  举报