Bun Redis Crapper - 生产准备
Bun 强大的 Redis 包装 生产准备控制器 用于构建真正的应用程序。 会话的滴入解决方案,缓存,速率限制,工作队列等等.
初学者快速启动
备选案文1:使用生产控制器(建议)
import { createRedis } from "@codecaine/bun-redis-wrapper";
import { SessionController, CacheController } from "@codecaine/bun-redis-wrapper/controllers";
const redis = await createRedis();
// Sessions - ready to use!
const sessions = new SessionController(redis);
const sessionId = await sessions.create("user-123", { name: "Alice" });
// Caching - intelligent and automatic!
const cache = new CacheController(redis);
const user = await cache.getOrSet("user:123", () => db.getUser(123), 300);
* 可用的控制器 :
- 会话控制器 - 有多设备支持的用户会话
- 缓存控制器 - 有缓存-侧式的智能缓存
- 速率控制器 - API费率限制(固定/滑行窗口、象征性桶)
- 队列控制器 - 背景工作处理与优先事项
- 存储控制器 - JSON的简单密钥值存储
- 分析管理员 - 使用HyperLogLog进行计量跟踪
- PubSub 主计长 - 出版/订阅通讯
- 锁定控制器 - 分布式锁(小哑巴)
- 领导板控制器 - 排名和领跑板(各种套)
- 柜台管理员 - 原子计数器和统计器
- 公式管理员 - 示例域控制器(保健公式)
- RadApp 控制器 - 示例域控制器(RAD app模式)
👉 文档 - 附有实例的完整指南
👉 示例应用程序 - 使用所有控制器的全应用程序
备选案文2:直接使用核心包装
import { createRedis, createNamespacedRedis } from "@codecaine/bun-redis-wrapper";
await using redis = await createRedis("redis://localhost:6379");
await redis.set("key", "value");
// With namespaces
const authApp = createNamespacedRedis(redis, "auth");
const shopApp = createNamespacedRedis(redis, "shop");
* 特性
✅ 生产准备控制器 - 常见案例的即时解决办法
✅ 初学者友好 - 明确的文件和实例
✅ 类型安全 - 有适当类型的全部类型脚本支持
✅ 命名空间支持 - 防止相撞的自动密钥前缀
✅ 综合 API - 支助所有共同的Redis行动
✅ JSON 帮助者 - JSON系列化/去序化
✅ 排序的集 - 领导板、排名和优先排队
✅ 流线 - 事件来源和实时数据处理
✅ 地理空间 - 基于地点的查询和近距离搜索
✅ 超日志 - 内存效率独特的计数
✅ 自动处理 - 与 await using 语法
✅ 无依赖 - 使用 Bun 的本地 Redisclient 软件
QQ 支持的 Redis 数据类型
- 字符串 - 获取,SET,INCR,DECR
- 哈谢斯 - 赫特,赫特,赫特尔
- 名单 - LPUSH, RPUSH, 上帝军
- 设定 - 萨德、塞缪尔、塞缪尔
- 排序的集 - ZANDD,ZRANGE,ZRANK(领跑板)
- 流线 - XADD、XREAD、XRANGE(活动日志)
- 地理空间 乔治,乔治,乔治
- 超日志 - PFADD, PFCOUNT(独特的计算)
页:1
初学者
本地运行所有演示 :
bun run demos
高级用户
- API.md (英语) - 填写所有方法的API参考
- (中文(简体) ). md - Redis特征覆盖分析
- 中文翻译: - 常见的作弊表
- 指数. test.ts - 全套测试套件(83个测试)
* 安装
# Using Bun
bun add @codecaine/bun-redis-wrapper
# Using npm
npm install @codecaine/bun-redis-wrapper
# Using pnpm
pnpm add @codecaine/bun-redis-wrapper
# Using yarn
yarn add @codecaine/bun-redis-wrapper
QQ 快例
届会(制作-准备)
import { SessionController } from "@codecaine/bun-redis-wrapper/controllers";
const sessions = new SessionController(redis);
// Create session
const sessionId = await sessions.create("user-123", {
name: "Alice",
email: "[email protected]"
});
// Validate session
const session = await sessions.validate(sessionId);
if (session) {
console.log(`Welcome ${session.data.name}!`);
}
// Logout
await sessions.destroy(sessionId);
缓存( 生产- 准备)
import { CacheController } from "@codecaine/bun-redis-wrapper/controllers";
const cache = new CacheController(redis);
// Cache-aside pattern (automatic!)
const user = await cache.getOrSet(
"user:123",
async () => await database.getUser(123), // Only called on cache miss
300 // Cache for 5 minutes
);
// Check cache stats
const stats = await cache.getStats();
console.log(`Hit rate: ${stats.hitRate}%`);
限制费率(生产-准备)
import { RateLimiterController } from "@codecaine/bun-redis-wrapper/controllers";
const limiter = new RateLimiterController(redis);
// Check rate limit (10 requests per minute)
const result = await limiter.check("user-123", 10, 60);
if (!result.allowed) {
throw new Error(`Rate limited. Retry after ${result.retryAfter}s`);
}
console.log(`${result.remaining} requests remaining`);
背景工作(生产-准备)
import { QueueController } from "@codecaine/bun-redis-wrapper/controllers";
const queue = new QueueController(redis);
// Add job
await queue.add("send-email", {
to: "[email protected]",
subject: "Welcome!"
}, { priority: 8 });
// Process jobs (in worker)
const job = await queue.next();
if (job) {
await sendEmail(job.data);
await queue.complete(job.id);
}
核心包装使用
### Multi-Tenant Application
```typescript
import { createRedis, createNamespacedRedis } from "@codecaine/bun-redis-wrapper";
await using redis = await createRedis();
// Each tenant gets isolated namespace
const tenant1 = createNamespacedRedis(redis, "tenant:acme");
const tenant2 = createNamespacedRedis(redis, "tenant:globex");
await tenant1.setJSON("config", { theme: "dark" });
await tenant2.setJSON("config", { theme: "light" });
// No collisions - each tenant has separate data
环境隔离
const env = process.env.NODE_ENV || "development";
const namespace = `myapp:${env}`;
const redis = createNamespacedRedis(baseRedis, namespace);
// Keys stored as: "myapp:development:..." or "myapp:production:..."
API 参考
工厂功能
createRedis(url?: string)
创建基础 Redis 连接 .
await using redis = await createRedis("redis://localhost:6379");
createNamespacedRedis(redis, namespace)
创建带有自动密钥前缀的命名空间包.
const app = createNamespacedRedis(redis, "myapp");
clearNamespace(redis, namespace)
删除命名空间中的所有密钥.
const deleted = await clearNamespace(redis, "myapp");
#### `copyNamespace(redis, fromNamespace, toNamespace, options?)`
Copies all keys from one namespace to another (useful for dev → staging → prod promotions within the same Redis instance).
```typescript
const result = await copyNamespace(redis, "myapp:dev", "myapp:staging", { replace: false });
console.log(result); // { scanned, copied, skipped }
### Available Operations
All operations support both the base `RedisWrapper` and `NamespacedRedisWrapper`:
**Core Operations**
- `get(key)`, `set(key, value, options?)`
- `del(...keys)`, `exists(...keys)`
**JSON Operations**
- `getJSON<T>(key)`, `setJSON<T>(key, value, options?)`
**Multi Operations**
- `mget(...keys)`, `mset(data)`
**Hash Operations**
- `hget(key, field)`, `hset(key, field, value)`
- `hmget(key, ...fields)`, `hmset(key, data)`
- `hgetAll(key)`
**Counter Operations**
- `incr(key)`, `decr(key)`
**TTL Operations**
- `ttl(key)`, `setTTL(key, seconds)`, `expire(key, seconds)`
**Pattern Matching**
- `scanAll(pattern, count?)`
**Pub/Sub**
- `subscribe(channel, callback)`, `publish(channel, message)`
**List Operations**
- `lpush(key, ...values)`, `rpush(key, ...values)`
- `lrange(key, start?, stop?)`, `lpop(key)`, `rpop(key)`
**Set Operations**
- `sadd(key, ...members)`, `srem(key, ...members)`, `smembers(key)`
## Examples
### JSON Storage with TTL
```typescript
interface UserSession {
userId: number;
username: string;
loginAt: number;
}
const sessions = createNamespacedRedis(redis, "sessions");
const session: UserSession = {
userId: 123,
username: "alice",
loginAt: Date.now()
};
// Store with 1 hour expiration
await sessions.setJSON("user:123", session, { EX: 3600 });
// Retrieve
const active = await sessions.getJSON<UserSession>("user:123");
限制费率
async function checkRateLimit(
client: NamespacedRedisWrapper,
userId: string,
maxRequests: number,
windowSeconds: number
): Promise<boolean> {
const key = `ratelimit:${userId}`;
const count = await client.incr(key);
if (count === 1) {
await client.setTTL(key, windowSeconds);
}
return count <= maxRequests;
}
const api = createNamespacedRedis(redis, "api:v1");
const allowed = await checkRateLimit(api, "user:123", 10, 60);
模式匹配
const app = createNamespacedRedis(redis, "myapp");
// Store user sessions
await app.set("session:user:1", "data1");
await app.set("session:user:2", "data2");
await app.set("config:timeout", "30");
// Find all sessions (scoped to namespace)
const sessionKeys = await app.scanAll("session:*");
console.log(sessionKeys); // ["session:user:1", "session:user:2"]
最佳做法
1. 使用一致命名
// ✅ Good: Clear hierarchy with colons
"app:entity:id:field"
"myapp:user:12345:profile"
// ❌ Avoid: Inconsistent separators
"myapp_user_12345"
2. 共享基础连接
// ✅ Good: One connection, multiple namespaces
await using redis = await createRedis();
const app1 = createNamespacedRedis(redis, "app1");
const app2 = createNamespacedRedis(redis, "app2");
// ❌ Bad: Multiple connections
const redis1 = await createRedis();
const redis2 = await createRedis();
3. 测试中的清理
import { test, afterEach } from "bun:test";
afterEach(async () => {
await clearNamespace(redis, "test");
});
使用大小写
- 🏢 微服务 - 将每项服务的数据隔离
- 👥 多租户SaaS - 每个客户分别提供数据
- 🌍 环境隔离 - 断层/断层/断层分离
- 🔄 API 版本 - v1/v2 命名空间隔离
- 👨💻 团队资源 - 基于小组的出入控制
业绩
命名空间包装器添加了最小的间接费用 - 只是字符串连接. 没有额外的网络呼叫或内存管理.
测试
运行综合测试套件 :
# Run all tests
bun test
# Run tests in watch mode
bun test --watch
测试套间包括83个测试,涵盖:
- 核心雷迪斯行动
- JSON业务
- 多种业务
- 散列作业
- 反恐行动
- TTL 业务
- 模式匹配
- 列表操作
- 设置操作
- 命名空间隔离
- 多租户方案
- 融合测试
所需资源
- Bun v1.0+ 设备
- Redis 服务器
许可证
麻省理工学院