Upstash
Upstash 是专为 Serverless 和 Edge 环境设计的数据库服务,提供 Redis、Kafka 和 Vector 数据库。其核心优势是基于 HTTP/REST 的连接方式,非常适合在 Cloudflare Workers、Vercel Edge Functions 等无状态环境中使用。
1. 为什么选择 Upstash?
- Serverless 架构:按需付费,无需管理服务器,自动缩容至零。
- HTTP 接口:传统的 Redis 使用 TCP 连接,在 Serverless 场景下容易因并发过高耗尽连接池。Upstash 提供 REST 客户端,使用无状态的 HTTP 请求。
- Edge 兼容:完美支持所有 Edge Runtime 平台。
2. Upstash Redis 集成
安装 SDK
npm install @upstash/redis
初始化
import { Redis } from "@upstash/redis";
const redis = new Redis({
url: "https://REGION-NAME.upstash.io",
token: "YOUR_SECRET_TOKEN",
});
基础用法
// 设置值 (支持超时)
await redis.set("foo", "bar", { ex: 3600 });
// 获取值
const data = await redis.get("foo");
// 使用原子操作
await redis.incr("counter");
3. Upstash Vector (向量数据库)
适用于 AI 应用(如 RAG 检索、语义搜索)。
核心操作
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
// 插入向量
await index.upsert({
id: "id1",
vector: [0.1, 0.2, 0.3, ...],
metadata: { title: "Hello Vector" }
})
// 查询相似内容
const results = await index.query({
vector: [0.1, 0.2, 0.4],
topK: 5,
includeMetadata: true,
})
4. 在 React / Next.js 中的实践
由于 Upstash 运行在服务端(或 Edge 端),在 React 应用中通常分为 Server Components (RSC) 直接调用和 API Routes 中转调用。
在 Next.js Server Components 中使用
可以直接在组件中调用而不必担心连接池耗尽。
// app/page.tsx
import { Redis } from "@upstash/redis";
const redis = Redis.fromEnv(); // 自动读取环境变量
export default async function Page() {
const views = await redis.incr("page_views");
return <div>当前访问量: {views}</div>;
}
配合 API Route 实现请求限流 (Rate Limiting)
这是 Upstash 最火的使用方案之一,防止接口被恶意刷量。
// middleware.ts 或 api/route.ts
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, "10 s"), // 每 10 秒限制 10 次请求
});
export async function middleware(request) {
const ip = request.ip ?? "127.0.0.1";
const { success, limit, remaining } = await ratelimit.limit(ip);
if (!success) return new Response("Too Many Requests", { status: 429 });
}
5. 典型场景
- API 限流 (Rate Limiting):利用 Redis 的快速读写和原子计数,结合
@upstash/ratelimit。 - 全局状态缓存:在不同地区的 Edge Functions 之间共享状态。
- AI RAG (向量检索):使用
@upstash/vector存储经过 Embedding 的知识库,供 React 前端进行语义搜索。
6. HTTP vs TCP
| 特性 | 传统 Redis (TCP) | Upstash Redis (HTTP) |
|---|---|---|
| 连接模型 | 有状态 (长连接) | 无状态 (短连接) |
| Serverless 友好度 | 差 (容易耗尽连接数) | 优 (无连接数限制) |
| 安全性 | 需要 VPC 或防火墙 | 内置 Token 验证 |
| Edge 支持 | 受限 (部分环境不支持 TCP) | 全面支持 |
参考资源: