# @codecaine/bun-redis-wrapper 中文文档

规范地址：https://npmcn.com/package/%40codecaine/bun-redis-wrapper/

版本：1\.2\.1
npm 元数据更新时间：2025-12-27T14:24:15.702Z
中文译文更新时间：2026-11-10T06:34:27.903Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40codecaine/bun-redis-wrapper
原文对照：https://npmcn.com/package/%40codecaine/bun-redis-wrapper/?lang=original
项目主页：https://github.com/codecaine-zz/bun_redis_wrapper#readme
源码仓库：https://github.com/codecaine-zz/bun_redis_wrapper

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：359 kB，63 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=18\.0\.0
- 运行依赖：0 个
- peer 依赖：bun \>=1\.0\.0
- 首次发布：2025-12-27T13:20:35.351Z
- 最新版本发布：2025-12-27T14:24:15.492Z
- 近 30 天下载量：3451（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：3（近 12 个月 3 个）

## 中文简介

装有命名空间、控制器和TypeScript支持的 Bun 生产准备的 Redis 包装器

## 安装

```sh
npm install @codecaine/bun-redis-wrapper
```

也可以使用：`pnpm add @codecaine/bun-redis-wrapper`、`yarn add @codecaine/bun-redis-wrapper`、`bun add @codecaine/bun-redis-wrapper`

## README

# Bun Redis Crapper - 生产准备

[![npm version](https://img.shields.io/npm/v/@codecaine/bun-redis-wrapper.svg)](https://www.npmjs.com/package/@codecaine/bun-redis-wrapper) [![npm downloads](https://img.shields.io/npm/dm/@codecaine/bun-redis-wrapper.svg)](https://www.npmjs.com/package/@codecaine/bun-redis-wrapper) [![license](https://img.shields.io/npm/l/@codecaine/bun-redis-wrapper.svg)](https://github.com/codecaine-zz/bun_redis_wrapper/blob/main/LICENSE)

Bun 强大的 Redis 包装 **生产准备控制器** 用于构建真正的应用程序。 会话的滴入解决方案,缓存,速率限制,工作队列等等.

## 初学者快速启动

### 备选案文1:使用生产控制器(建议)

```typescript
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模式)

👉 **[文档](https://npmcn.com/package/%40codecaine/bun-redis-wrapper/src/controllers/README.md)** - 附有实例的完整指南  
👉 **[示例应用程序](https://npmcn.com/package/%40codecaine/bun-redis-wrapper/demos/14-controller-app.ts)** - 使用所有控制器的全应用程序

### 备选案文2:直接使用核心包装

```typescript
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

### 初学者

-   **[主计长指南](https://npmcn.com/package/%40codecaine/bun-redis-wrapper/src/controllers/README.md)** - 生产准备控制器 此处开始
-   **[示例应用程序](https://npmcn.com/package/%40codecaine/bun-redis-wrapper/demos/14-controller-app.ts)** - 完整的应用示例
-   **[演示文稿](https://npmcn.com/package/%40codecaine/bun-redis-wrapper/demos/)** - 有最佳做法的15个全面实例

本地运行所有演示 :

```bash
bun run demos
```

### 高级用户

-   **[API.md (英语)](https://npmcn.com/package/%40codecaine/bun-redis-wrapper/docs/API.md)** - 填写所有方法的API参考
-   **[(中文(简体) ). md](https://npmcn.com/package/%40codecaine/bun-redis-wrapper/docs/REDIS_FEATURES.md)** - Redis特征覆盖分析
-   **[中文翻译:](https://npmcn.com/package/%40codecaine/bun-redis-wrapper/docs/QUICK_REFERENCE.md)** - 常见的作弊表
-   **[指数. test.ts](https://npmcn.com/package/%40codecaine/bun-redis-wrapper/tests/index.test.ts)** - 全套测试套件(83个测试)

## \* 安装

```bash
# 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 快例

### 届会(制作-准备)

```typescript
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: "alice@example.com"
});

// Validate session
const session = await sessions.validate(sessionId);
if (session) {
  console.log(`Welcome ${session.data.name}!`);
}

// Logout
await sessions.destroy(sessionId);
```

### 缓存( 生产- 准备)

```typescript
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}%`);
```

### 限制费率(生产-准备)

```typescript
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`);
```

### 背景工作(生产-准备)

```typescript
import { QueueController } from "@codecaine/bun-redis-wrapper/controllers";

const queue = new QueueController(redis);

// Add job
await queue.add("send-email", {
  to: "user@example.com",
  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
````

### 环境隔离

```typescript
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 连接 .

```typescript
await using redis = await createRedis("redis://localhost:6379");
```

#### `createNamespacedRedis(redis, namespace)`

创建带有自动密钥前缀的命名空间包.

```typescript
const app = createNamespacedRedis(redis, "myapp");
```

#### `clearNamespace(redis, namespace)`

删除命名空间中的所有密钥.

````typescript
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");
````

### 限制费率

```typescript
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);
```

### 模式匹配

```typescript
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\. 使用一致命名

```typescript
// ✅ Good: Clear hierarchy with colons
"app:entity:id:field"
"myapp:user:12345:profile"

// ❌ Avoid: Inconsistent separators
"myapp_user_12345"
```

### 2\. 共享基础连接

```typescript
// ✅ 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\. 测试中的清理

```typescript
import { test, afterEach } from "bun:test";

afterEach(async () => {
  await clearNamespace(redis, "test");
});
```

## 使用大小写

-   🏢 **微服务** - 将每项服务的数据隔离
-   👥 **多租户SaaS** - 每个客户分别提供数据
-   🌍 **环境隔离** - 断层/断层/断层分离
-   🔄 **API 版本** - v1/v2 命名空间隔离
-   👨‍💻 **团队资源** - 基于小组的出入控制

## 业绩

命名空间包装器添加了最小的间接费用 - 只是字符串连接. 没有额外的网络呼叫或内存管理.

## 测试

运行综合测试套件 :

```bash
# Run all tests
bun test

# Run tests in watch mode
bun test --watch
```

测试套间包括83个测试,涵盖:

-   核心雷迪斯行动
-   JSON业务
-   多种业务
-   散列作业
-   反恐行动
-   TTL 业务
-   模式匹配
-   列表操作
-   设置操作
-   命名空间隔离
-   多租户方案
-   融合测试

## 所需资源

-   Bun v1.0+ 设备
-   Redis 服务器

## 许可证

麻省理工学院

* * *

## 常见问题

### @codecaine/bun-redis-wrapper 是什么？

装有命名空间、控制器和TypeScript支持的 Bun 生产准备的 Redis 包装器

### 如何安装 @codecaine/bun-redis-wrapper？

在项目目录运行 npm install @codecaine/bun-redis-wrapper，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：bun（\>=1\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @codecaine/bun-redis-wrapper 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @codecaine/bun-redis-wrapper 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @codecaine/bun-redis-wrapper 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @codecaine/bun-redis-wrapper 可以商用吗？

@codecaine/bun-redis-wrapper 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @codecaine/bun-redis-wrapper 的下载量有多少？

根据 npm 官方下载统计，@codecaine/bun-redis-wrapper 在 2026/10/10 – 2026/11/08 这 30 天内被下载 3,451 次，日均约 115 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @codecaine/bun-redis-wrapper 还在维护吗？

最新版本 1\.2\.1 发布于 2025/12/27（10 个月前）；至今共发布 3 个版本，其中过去 12 个月发布了 3 个；首次发布于 2025/12/27。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

