🔴 概述
Upstash Redis 是完全托管的 Redis 服务,提供:
- 完整协议:支持所有 Redis 命令
- 低延迟:2-5ms 全球平均延迟
- 持久化:内存 + 磁盘双重存储
- HTTP API:支持无 TCP 环境
📚 数据结构
字符串 (String)
javascript
await redis.set('key', 'value')
await redis.set('counter', 100)
await redis.incr('counter') // 101
// 带过期
await redis.setex('session', 3600, 'data') // 1小时后过期
// 条件设置
await redis.setnx('lock', '1') // 仅当不存在时设置
哈希 (Hash)
javascript
await redis.hset('user:1', { name: 'John', age: 30 })
await redis.hget('user:1', 'name') // "John"
await redis.hgetall('user:1') // { name: "John", age: "30" }
await redis.hdel('user:1', 'age')
列表 (List)
javascript
await redis.lpush('queue', 'task1', 'task2')
await redis.rpush('queue', 'task3')
await redis.lpop('queue') // "task2"
await redis.lrange('queue', 0, -1) // ["task1", "task3"]
集合 (Set)
javascript
await redis.sadd('tags', 'redis', 'database', 'nosql')
await redis.sismember('tags', 'redis') // 1
await redis.smembers('tags') // ["redis", "database", "nosql"]
有序集合 (Sorted Set)
javascript
await redis.zadd('leaderboard', 100, 'player1')
await redis.zadd('leaderboard', 200, 'player2')
await redis.zrange('leaderboard', 0, -1, { rev: true }) // 排行榜
🔒 常见用例
缓存
javascript
async function getCached(key, fetcher, ttl = 3600) {
const cached = await redis.get(key)
if (cached) return cached
const data = await fetcher()
await redis.setex(key, ttl, JSON.stringify(data))
return data
}
// 使用
const user = await getCached('user:1', () => fetchUser(1))
限流
javascript
async function rateLimit(key, limit, window) {
const current = await redis.incr(key)
if (current === 1) {
await redis.expire(key, window)
}
return current <= limit
}
// 每分钟最多 100 请求
if (await rateLimit('api:user:1', 100, 60)) {
// 允许
} else {
// 拒绝
}
会话存储
javascript
await redis.setex('session:abc123', 86400, JSON.stringify({
userId: 1,
role: 'admin'
}))
const session = JSON.parse(await redis.get('session:abc123'))
⚡ 性能优化
- 使用 Pipeline 批量操作
- 选择最近的区域
- 使用连接复用
- 避免大 Key(>1MB)