python操作Redis

1. 使用Homebrew安装Redis

To install Redis using Homebrew on macOS, follow these steps:

1.Update Homebrew

Before installing anything, it’s good practice to ensure Homebrew is up to date. Open your terminal and run:

brew update
  1. Install Redis

Use the following command to install Redis:

brew install redis
  1. Verify Installation

After installation, verify that Redis has been installed by checking its version:

redis-server --version
  1. Start Redis Service

Start the Redis service using Homebrew:

brew services start redis
  1. Test Redis

To test if Redis is running properly:

redis-cli ping

If Redis is running, you should see the response:

PONG
  1. Optional: Stop Redis Service

If you need to stop the Redis service:

brew services stop redis
  1. Optional: Restart Redis Service

If you need to restart the Redis service:

brew services restart redis

2. Python 操作 Redis

  1. 安装依赖

    pip install redis[hiredis]
  2. 连接 Redis

    import redis
    # 创建连接
    r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
    # 或使用 Redis 类
    r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
  3. 字符串操作

    ​ • set(name, value, ex=None, px=None, nx=False, xx=False):设置字符串键值。

    ​ • get(name):获取字符串值。

    ​ • mset(mapping):批量设置键值。

    ​ • mget(keys):批量获取键值。

    ​ • incr(name, amount=1):自增字符串。

    ​ • decr(name, amount=1):自减字符串。

    ​ • append(key, value):向字符串追加值。

    r.set('key', 'value', ex=10) # 设置键,10 秒后过期
    print(r.get('key')) # 获取键值
    r.incr('counter') # 自增
  4. 哈希 (Hash) 操作

    ​ • hset(name, key, value):设置哈希字段。

    ​ • hget(name, key):获取哈希字段。

    ​ • hmset(name, mapping):批量设置哈希字段(新版中建议用 hset 替代)。

    ​ • hmget(name, keys):批量获取哈希字段值。

    ​ • hdel(name, *keys):删除哈希字段。

    ​ • hgetall(name):获取哈希的所有字段和值。

    r.hset('hash_key', 'field1', 'value1')
    print(r.hget('hash_key', 'field1'))
    r.hset('hash_key', mapping={'field2': 'value2', 'field3': 'value3'})
    print(r.hgetall('hash_key'))
  5. 列表 (List) 操作

    ​ • lpush(name, values):从左侧插入元素。

    ​ • rpush(name, values):从右侧插入元素。

    ​ • lpop(name):移出并返回左侧第一个元素。

    ​ • rpop(name):移出并返回右侧第一个元素。

    ​ • lrange(name, start, end):获取列表指定范围的元素。

    r.lpush('list_key', 'a', 'b', 'c')
    print(r.lrange('list_key', 0, -1)) # ['c', 'b', 'a']
    r.rpop('list_key') # 'a'
  6. 集合 (Set) 操作

    ​ • sadd(name, *values):添加集合元素。

    ​ • srem(name, *values):移除集合元素。

    ​ • smembers(name):获取集合所有元素。

    ​ • sismember(name, value):检查是否是集合成员。

    r.sadd('set_key', 'a', 'b', 'c')
    print(r.smembers('set_key')) # {'a', 'b', 'c'}
    r.srem('set_key', 'a')
  7. 有序集合 (Sorted Set) 操作

    ​ • zadd(name, mapping, nx=False, xx=False, ch=False, incr=False):添加或更新有序集合。

    ​ • zrange(name, start, end, desc=False, withscores=False):获取有序集合的范围。

    ​ • zrem(name, *values):移除有序集合中的元素。

    r.zadd('zset_key', {'a': 1, 'b': 2, 'c': 3})
    print(r.zrange('zset_key', 0, -1, withscores=True))
    r.zrem('zset_key', 'a')
  8. 键管理

    ​ • delete(*names):删除键。

    ​ • exists(name):检查键是否存在。

    ​ • expire(name, time):设置键的过期时间。

    ​ • ttl(name):获取键的剩余时间。

    r.set('temp_key', 'value')
    r.expire('temp_key', 30) # 设置过期时间 30 秒
    print(r.ttl('temp_key'))
  9. 事务

    ​ • 使用 pipeline 实现事务操作。

    pipe = r.pipeline()
    pipe.set('key1', 'value1')
    pipe.set('key2', 'value2')
    pipe.execute()
  10. 发布/订阅

    ​ • publish(channel, message):发布消息。

    ​ • subscribe(*channels):订阅频道。

    # 发布
    r.publish('channel', 'message')
    # 订阅
    ps = r.pubsub()
    ps.subscribe('channel')
    for message in ps.listen():
    print(message)
  11. 其他操作

    ​ • flushdb():清空当前数据库。

    ​ • flushall():清空所有数据库。

    r.flushdb() # 慎用
    r.flushall() # 慎用

    如果需要更高级的功能(如连接池、异步支持等),redis-py 也提供了相应的支持。可以根据需求深入研究。

3. FastAPI与Redis集成

FastAPI 与 Redis 的集成通常用于缓存、任务队列、会话管理或数据存储等用途。下面介绍如何将 FastAPI 与 Redis 结合使用。

1. 安装依赖

你需要安装以下依赖项:

pip install fastapi uvicorn redis[asyncio]

​ • fastapi:FastAPI 框架

​ • uvicorn:ASGI 服务器

​ • redis[asyncio]:Redis 的异步客户端(基于 aioredis)

2. 连接 Redis

FastAPI 使用 redis.asyncio 进行异步 Redis 操作,以下是如何在 FastAPI 应用中初始化 Redis 连接的方法:

创建 Redis 客户端

from fastapi import FastAPI, Depends
import redis.asyncio as redis
app = FastAPI()
# Redis 连接池
async def get_redis():
redis_client = await redis.from_url("redis://localhost:6379", decode_responses=True)
try:
yield redis_client
finally:
await redis_client.close()

3. 使用 Redis 进行数据存取

存储和获取键值

@app.post("/set/")
async def set_value(key: str, value: str, redis_client: redis.Redis = Depends(get_redis)):
await redis_client.set(key, value)
return {"message": "Value stored successfully"}
@app.get("/get/")
async def get_value(key: str, redis_client: redis.Redis = Depends(get_redis)):
value = await redis_client.get(key)
if value is None:
return {"message": "Key not found"}
return {"key": key, "value": value}

4. 使用 Redis 进行缓存

可以使用 Redis 进行 API 响应缓存,提高性能。

from fastapi import Query
import time
@app.get("/cached-data/")
async def get_cached_data(q: str = Query(...), redis_client: redis.Redis = Depends(get_redis)):
cache_key = f"query:{q}"
# 尝试获取缓存
cached_value = await redis_client.get(cache_key)
if cached_value:
return {"source": "cache", "data": cached_value}
# 模拟数据处理
time.sleep(2)
data = f"Processed data for query: {q}"
# 存入 Redis 缓存,设置 10 秒过期时间
await redis_client.setex(cache_key, 10, data)
return {"source": "generated", "data": data}

5. Redis 作为消息队列

可以使用 Redis 的 RPUSH 和 LPOP 实现简单的任务队列。

生产者

@app.post("/enqueue/")
async def enqueue_task(task: str, redis_client: redis.Redis = Depends(get_redis)):
await redis_client.rpush("task_queue", task)
return {"message": "Task added to queue"}

消费者

@app.get("/dequeue/")
async def dequeue_task(redis_client: redis.Redis = Depends(get_redis)):
task = await redis_client.lpop("task_queue")
if task:
return {"task": task}
return {"message": "No tasks in queue"}

6. 运行 FastAPI

启动 FastAPI 服务器:

uvicorn main:app --reload

确保 Redis 服务器已启动:

redis-server

然后,你可以通过浏览器或 Postman 访问:

​ • POST /set/?key=name&value=Leo

​ • GET /get/?key=name

​ • GET /cached-data/?q=example

​ • POST /enqueue/?task=task1

​ • GET /dequeue/

总结

​ • 连接 Redis 使用 redis.asyncio。

​ • 使用 set() 和 get() 存储和获取数据。

​ • setex() 进行缓存处理。

​ • RPUSH 和 LPOP 作为任务队列。

这样,你就成功地将 FastAPI 与 Redis 进行了集成!🚀

4. 使用Redis连接池

在 FastAPI 中使用 Redis 连接池 可以提高 Redis 访问的性能,减少连接创建和释放的开销。以下是使用 redis.asyncio.ConnectionPool 来管理连接池的方式。

1. 安装 Redis 依赖

首先,确保安装了 redis[asyncio] 以支持异步操作:

pip install redis[asyncio] fastapi uvicorn

2. 通过 FastAPI 全局管理 Redis 连接池

在 FastAPI 中,我们可以在 应用启动时 创建 Redis 连接池,并在应用关闭时释放它。这样可以避免每次请求都创建新的 Redis 连接。

完整代码示例

from fastapi import FastAPI, Depends
import redis.asyncio as redis
app = FastAPI()
# 定义 Redis 连接池
redis_pool: redis.ConnectionPool = None
# 在应用启动时创建 Redis 连接池
@app.on_event("startup")
async def startup_event():
global redis_pool
redis_pool = redis.ConnectionPool.from_url(
"redis://localhost:6379", decode_responses=True, max_connections=10
)
# 在应用关闭时释放 Redis 连接池
@app.on_event("shutdown")
async def shutdown_event():
if redis_pool:
await redis_pool.disconnect()
# 获取 Redis 连接
async def get_redis():
redis_client = redis.Redis(connection_pool=redis_pool)
try:
yield redis_client
finally:
await redis_client.close() # 关闭 Redis 客户端(但连接池仍然存在)
# 测试 Redis 连接
@app.post("/set/")
async def set_value(key: str, value: str, redis_client: redis.Redis = Depends(get_redis)):
await redis_client.set(key, value)
return {"message": "Value stored successfully"}
@app.get("/get/")
async def get_value(key: str, redis_client: redis.Redis = Depends(get_redis)):
value = await redis_client.get(key)
if value is None:
return {"message": "Key not found"}
return {"key": key, "value": value}

3. 代码解析

​ • 使用 ConnectionPool.from_url() 预创建连接池,这样每次访问 Redis 时不需要重复建立新连接,提高性能。

​ • max_connections=10 限制最大连接数,防止连接池过载。

​ • @on_event("startup") & @on_event("shutdown") 用于管理 Redis 连接池的生命周期。

​ • Depends(get_redis) 通过依赖注入管理 Redis 客户端,每次请求都从连接池获取 Redis 连接。

4. 运行和测试

启动 FastAPI 服务器:

uvicorn main:app --reload

确保 Redis 服务器在运行:

redis-server

然后你可以使用以下 API 进行测试:

​ 1. 存储键值

curl -X POST "http://127.0.0.1:8000/set/?key=username&value=Leo"

​ 2. 获取键值

curl -X GET "http://127.0.0.1:8000/get/?key=username"

5. 连接池的好处

​ • 减少重复连接:避免每个请求都创建新连接,提升性能。

​ • 提高吞吐量:适用于高并发应用,如 API 网关或 WebSocket 服务器。

​ • 更好的资源管理:防止 Redis 连接数暴涨,影响数据库稳定性。

这样,你的 FastAPI 应用就可以高效地使用 Redis 连接池了!🚀

posted on   朝朝暮Mu  阅读(4)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示