mcpField
R
redis

redis

github.com/thelobbi数据与数据库2146 次安装2 天前更新
代码仓库

关于 redis

面向 Golden Armada AI Agent Fleet Platform 的 Redis 技能,涵盖常见数据存储与协调模式,并提供 CLI 和 Python 示例。内容包括缓存、会话、消息传递、速率限制和分布式锁。

主要功能

  1. 01Redis CLI 连接与命令
  2. 02同步及异步 Python 示例
  3. 03缓存旁路模式与失效处理
  4. 04速率限制与分布式锁
  5. 05发布订阅与会话管理

适用场景

  1. 01实现带过期时间的缓存
  2. 02使用 Redis 哈希管理会话
  3. 03按时间窗口限制请求速率
  4. 04通过分布式锁协调任务

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/thelobbi/claude --skill redis

安装后在 Claude Code 中输入/redis确认已加载。

详细介绍

Redis 技能

为 Golden Armada AI Agent Fleet Platform 提供全面的 Redis 功能。

何时使用此技能

在以下场景中启用此技能:

  • 缓存实现
  • 会话管理
  • Pub/Sub 消息传递
  • 速率限制
  • 分布式锁

Redis CLI 快速参考

连接

```bash

连接

redis-cli -h localhost -p 6379 redis-cli -h localhost -p 6379 -a password

测试连接

redis-cli ping ```

基本操作

```bash

字符串

SET key "value" SET key "value" EX 3600 # 设置 TTL GET key DEL key EXISTS key TTL key EXPIRE key 3600

哈希

HSET user:1 name "John" age "30" HGET user:1 name HGETALL user:1 HDEL user:1 age

列表

LPUSH queue "item1" RPUSH queue "item2" LPOP queue RPOP queue LRANGE queue 0 -1

集合

SADD tags "python" "redis" SMEMBERS tags SISMEMBER tags "python" SREM tags "python"

有序集合

ZADD leaderboard 100 "player1" 200 "player2" ZRANGE leaderboard 0 -1 WITHSCORES ZRANK leaderboard "player1" ZINCRBY leaderboard 50 "player1" ```

Python Redis 客户端

```python import redis from redis import asyncio as aioredis

同步客户端

r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)

异步客户端

async_redis = aioredis.from_url("redis://localhost:6379", decode_responses=True)

基本操作

r.set('key', 'value', ex=3600) value = r.get('key') r.delete('key')

哈希操作

r.hset('user:1', mapping={'name': 'John', 'age': '30'}) user = r.hgetall('user:1')

列表操作

r.lpush('queue', 'item1', 'item2') items = r.lrange('queue', 0, -1) item = r.rpop('queue')

异步操作

async def cache_get(key: str): async with aioredis.from_url("redis://localhost") as redis: return await redis.get(key) ```

缓存模式

Cache-Aside 模式

```python async def get_agent(agent_id: str) -> dict: # 先尝试读取缓存 cache_key = f"agent:{agent_id}" cached = await redis.get(cache_key) if cached: return json.loads(cached)

# 缓存未命中——从数据库获取
agent = await db.get_agent(agent_id)
if agent:
    await redis.set(cache_key, json.dumps(agent), ex=3600)

return agent

async def update_agent(agent_id: str, data: dict) -> dict: # 更新数据库 agent = await db.update_agent(agent_id, data)

# 使缓存失效
cache_key = f"agent:{agent_id}"
await redis.delete(cache_key)

return agent

```

速率限制

```python async def rate_limit(key: str, limit: int, window: int) -> bool: """ 滑动窗口速率限制器。 如果请求获准,则返回 True。 """ current = int(time.time()) window_key = f"rate:{key}:{current // window}"

async with redis.pipeline() as pipe:
    pipe.incr(window_key)
    pipe.expire(window_key, window * 2)
    results = await pipe.execute()

count = results[0]
return count <= limit

用法

if not await rate_limit(f"user:{user_id}", limit=100, window=60): raise HTTPException(status_code=429, detail="Rate limit exceeded") ```

分布式锁

```python import uuid

class DistributedLock: def init(self, redis_client, key: str, timeout: int = 10): self.redis = redis_client self.key = f"lock:{key}" self.timeout = timeout self.token = str(uuid.uuid4())

async def __aenter__(self):
    while True:
        acquired = await self.redis.set(
            self.key, self.token, nx=True, ex=self.timeout
        )
        if acquired:
            return self
        await asyncio.sleep(0.1)

async def __aexit__(self, exc_type, exc_val, exc_tb):
    # 仅在锁由当前实例持有时才释放
    script = """
    if redis.call("get", KEYS[1]) == ARGV[1] then
        return redis.call("del", KEYS[1])
    else
        return 0
    end
    """
    await self.redis.eval(script, 1, self.key, self.token)

用法

async with DistributedLock(redis, "resource:123"): await do_critical_work() ```

发布/订阅

```python

发布者

async def publish_event(channel: str, message: dict): await redis.publish(channel, json.dumps(message))

订阅者

async def subscribe_events(): pubsub = redis.pubsub() await pubsub.subscribe("agent:events")

async for message in pubsub.listen():
    if message["type"] == "message":
        data = json.loads(message["data"])
        await handle_event(data)

```

会话管理

```python from fastapi import Depends, HTTPException from fastapi.security import HTTPBearer import secrets

security = HTTPBearer()

async def create_session(user_id: str) -> str: session_id = secrets.token_urlsafe(32) session_key = f"session:{session_id}"

await redis.hset(session_key, mapping={
    "user_id": user_id,
    "created_at": datetime.utcnow().isoformat()
})
await redis.expire(session_key, 86400)  # 24 小时

return session_id

async def get_session(token: str = Depends(security)) -> dict: session_key = f"session:{token.credentials}" session = await redis.hgetall(session_key)

if not session:
    raise HTTPException(status_code=401, detail="Invalid session")

# 刷新 TTL
await redis.expire(session_key, 86400)
return session

```

最佳实践

  1. 在生产环境中使用连接池
  2. 为所有键设置 TTL,以防止内存膨胀
  3. 批量操作时使用流水线
  4. 针对连接问题实现适当的错误处理
  5. 使用 INFO memory 监控内存使用情况
  6. 使用 Lua 脚本执行原子操作

评论

支持 Markdown