# @cachehub/redis-cache 中文文档

规范地址：https://npmcn.com/package/%40cachehub/redis-cache/

版本：1\.0\.2
npm 元数据更新时间：2025-07-05T03:50:39.337Z
中文译文更新时间：2026-11-08T23:02:04.669Z
软件包许可：未声明

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

原始 npm 页面：https://www.npmjs.com/package/%40cachehub/redis-cache
原文对照：https://npmcn.com/package/%40cachehub/redis-cache/?lang=original

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

- 包体积（解压后）：57.6 kB，19 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2024-12-29T02:57:26.048Z
- 最新版本发布：2025-07-05T03:50:39.101Z
- 近 30 天下载量：14249（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：3（近 12 个月 0 个）

## 中文简介

## Overview Redis缓存适配器为 Redis 提供了密接字符串和 TypeCacheKey 支持的缓存库的具体执行. 这个适配器允许开发者在保持一致性的同时,将Redis作为缓存解决方案来杠杆化

## 安装

```sh
npm install @cachehub/redis-cache
```

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

## README

# Redis 快取适应器

## 概览

Redis缓存适配器提供了专为Redis提供的缓存库的实现,并附有混合字符串和TypeCacheKey支持. 这个适配器允许开发者利用Redis作为缓存解决方案,同时在不同的缓存执行间保持一致的API.

## 福利

-   **无缝一体化**:在不更改应用程序代码的情况下,将Redis缓存方便地整合到您的应用程序中.
-   **动态配置**: 配置缓存适配器,使用环境变量在不同的缓存策略之间切换.
-   **一般支助**: 存储并取回复杂对象,同时通过通用类型支持维护类型安全.
-   **混合密钥支持**: 支持字符串密钥和结构化的 TypeCacheKey 对象用于高级缓存管理.
-   **原生模式删除**: 使用 Redis SCAN + DEL 操作按模式删除多个缓存条目.
-   **即时一致性**: 所有操作都使用本地Redis命令提供即时一致性.

## 安装

要使用 Redis 缓存适配器, 请使用以下命令安装软件包 :

```bash
pnpm add @cachehub/redis-cache
```

## 配置

要配置 Redis 缓存适配器,请在应用程序中设置以下环境变量:

-   `CACHE_TYPE`: 设定为 `redis` 来使用 Redis 缓存适配器.
-   `CACHE_REDIS_URL`: Redis 服务器的 URL.

## 使用量

要在您的应用程序中使用 Redis 缓存适配器, 请遵循这些步骤 :

1.  导入 Redis 缓存包, 以注册到工厂 。 例如:
    
    ```typescript
    import '@cachehub/redis-cache';
    ```
    
2.  使用工厂创建缓存实例 .
3.  使用缓存实例设置、获取、删除并检查缓存条目.

### 示例

```typescript
import '@cachehub/redis-cache';
import { CacheFactoryFactory } from '@cachehub/core';

const factory = new CacheFactoryFactory();
const cache = await factory.createCache({
  CACHE_TYPE: 'redis-cache',
  CACHE_REDIS_URL: 'redis://localhost:6379'
});

// Set and get primitive types
await cache.set<string>('stringKey', 'myValue', 3600);
const stringValue = await cache.get<string>('stringKey');

await cache.set<number>('numberKey', 42, 3600);
const numberValue = await cache.get<number>('numberKey');

await cache.set<boolean>('booleanKey', true, 3600);
const booleanValue = await cache.get<boolean>('booleanKey');

// Set and get complex objects
interface User {
  id: number;
  name: string;
  email: string;
}

const user: User = {
  id: 1,
  name: 'John Doe',
  email: 'john@example.com'
};

await cache.set<User>('userKey', user);
const userValue = await cache.get<User>('userKey');

// Set and get arrays
await cache.set<string[]>('arrayKey', ['a', 'b', 'c']);
const arrayValue = await cache.get<string[]>('arrayKey');
console.log(value); // Output: 'myValue'

// Check if a key exists in the cache
const exists = await cache.has('myKey');
console.log(exists); // Output: true

// Delete a value from the cache
const deleted = await cache.delete('myKey');
console.log(deleted); // Output: true

// Check again if the key exists
const existsAfterDelete = await cache.has('myKey');
console.log(existsAfterDelete); // Output: false
```

### 类型缓存Key 用法

适配器支持高级情景的结构缓存密钥 :

```typescript
import type { TypeCacheKey } from '@cachehub/core';

// Using structured cache keys
const licenseKey: TypeCacheKey = {
  namespace: 'license',
  id: 'ABC-123',
  context: {
    action: 'activation',
    domain: 'example.com',
    ipAddress: '192.168.1.1'
  }
};

// Store with structured key
await cache.set(licenseKey, { token: 'xyz789', expires: Date.now() + 3600000 });

// Retrieve with structured key
const licenseData = await cache.get(licenseKey);

// Pattern deletion - delete all cache entries for license ABC-123
await cache.delete({
  namespace: 'license',
  id: 'ABC-123'
  // Omitting context deletes ALL entries matching namespace and id
});

// Delete all license entries
await cache.delete({
  namespace: 'license'
  // Omitting id deletes ALL entries in the namespace
});
```

### 模式删除支持

RedisCache 提供 **本地图案删除** 使用 Redis SCAN + DEL 操作进行即时一致性:

**支持全部删除模式 :**

```typescript
// Exact key deletion with TypeCacheKey
await cache.delete({ 
  namespace: 'license', 
  id: 'ABC-123',
  context: { action: 'activation', domain: 'example.com' }
});

// Namespace + ID deletion (deletes all contexts for that ID)
await cache.delete({ 
  namespace: 'license', 
  id: 'ABC-123' 
});

// Partial context deletion (deletes all entries matching partial context)
await cache.delete({ 
  namespace: 'license', 
  context: { action: 'activation' }  // Deletes all activations regardless of ID
});

// Namespace-only deletion (deletes all entries in namespace)
await cache.delete({ 
  namespace: 'license' 
});

// String key deletion
await cache.delete('exact-string-key');
```

**如何运作:**

-   **本地重做操作**: 使用 Redis SCAN 来有效匹配模式
-   **批处理**: 将按100分批处理的密钥用于最佳性能
-   **即时一致性**: 所有删除都是即时的(无 TTL 工作包)
-   **基于光标的扫描**: 高效处理大型密钥集而无需屏蔽

**删除模式 :**

-   ✅ **仅命名空格**数字 : `{ namespace: 'license' }` - 删除命名空间中的所有条目
-   ✅ **命名空间 + ID**数字 : `{ namespace: 'license', id: 'ABC-123' }` - 删除所有标识上下文
-   ✅ **部分内容**数字 : `{ namespace: 'license', context: { action: 'activation' } }` - 删除匹配的上下文
-   ✅ **精确删除**: 完整上下文的完整类型CacheKey
-   ✅ **字符串删除**: 直接字符串密钥

### 密钥序列化

TypeCacheKey 对象自动被序列化以决定字符串 :

-   `{ namespace: 'license', id: '123' }` → `'license|123'`
-   `{ namespace: 'license', id: '123', context: { action: 'activation' } }` → `'license|123|action:activation'`
-   为一致性按字母顺序排序上下文密钥

## 文件夹结构

Redis 缓存包的文件夹结构通常包括:

-   `src/`:包含包的源代码,包括:
    -   `Factory/`:包含用于创建缓存处理器的工厂类.
    -   `Cache/`: 包含执行缓存对象的类.
    -   `Type/`: 包含类型定义和接口.
-   `tests/`:包含包件的单位测试.
-   `README.md`: 包的文档.
-   `.env`: 配置的环境变量.

## 捐款

欢迎捐款! 随意叉出这个寄存器并提交拉取请求. 在提交之前,请确保您的代码通过所有起伏和单元测试.

您可以使用 :

```bash
pnpm format
```

您可以使用 :

```bash
pnpm test
```

您可以使用 :

```bash
# Requires Redis server running on localhost:6379 or REDIS_URL env var
REDIS_URL=redis://localhost:6379 pnpm test:integration
```

## 测试

这一一揽子计划包括全面测试范围:

### 单位测试

-   **模拟测试**: 使用被嘲笑的 Redis 客户端进行快速测试
-   **类型脚本汇编**: 确保类型安全和接口合规
-   **覆盖范围**: 键操作( 获得、 设定、 删除、 有) 有字符串和 TypeCacheKey
-   **模式删除**: 测试 Redis SCAN + DEL 模式匹配

### 整合测试

-   **真实的 Redis 环境**: 对 Redis 服务器进行测试
-   **TypeCacheKey 序列化**: 验证决定字符串转换
-   **模式删除**: 测试多级缓存无效方案
-   **立即一致性**: 校验本地 Redis 操作工作正确

### 运行测试

**1\. 单位测试(快速 -- -- 不要求重复)**

```bash
pnpm test
```

-   用被嘲笑的Redis客户端运行所有单位测试
-   测试 TypeCacheKey 功能、序列化和图案删除
-   以秒计完成

**2\. 综合试验(Reders Redis)**

```bash
# Start Redis server first
redis-server

# Run integration tests
REDIS_URL=redis://localhost:6379 pnpm test:integration
```

-   针对真正的 Redis 服务器的测试
-   验证所有 TypeCacheKey 模式正确工作
-   测试本地 Redis SCAN + DEL 操作

### 测试结构

```
tests/
├── Cache/
│   └── RedisCache.test.ts                    # Unit tests with mocks
├── Factory/
│   └── RedisCacheFactory.test.ts             # Factory unit tests
└── integration/
    └── RedisCache.integration.test.ts        # Real Redis integration tests
```

## 发展 工作流量

### 设置和建筑

```bash
# Install dependencies
pnpm install

# Build the package
pnpm build

# Check TypeScript compilation
pnpm check

# Format code
pnpm format
```

### 完成测试工作流程

```bash
# 1. Run unit tests
pnpm test

# 2. Test with real Redis (optional)
redis-server &  # Start Redis in background
REDIS_URL=redis://localhost:6379 pnpm test:integration
```

## 软件包状态摘要

**生产准备地物:**

-   使用混合字符串/对象密钥完成类型CacheKey支持
-   **本地 Redis 模式删除** 使用 SCAN + DEL 操作
-   综合测试覆盖率(20/20单位测试通过)
-   决定密钥序列化
-   立即一致性(无 TTL 工作轮廓)
-   真正的Redis环境的综合测试

**测试范围 :**

-   **单位测试(20/20)**: 所有核心功能经模拟验证
-   **综合测试(4/4)**: real Redis 服务器测试可用
-   **完全覆盖**: TypeCachey, 模式删除, 混合支持, 错误处理

**删除能力( 即时一致性 ):**

-   字符串密钥删除 : `cache.delete('key')` (即时)
-   精确删除类型CacheKey : `cache.delete({ namespace, id, context })` (即时)
-   删除命名空间 : `cache.delete({ namespace })` QQ( 高效SCAN )
-   命名空间 + ID 删除 : `cache.delete({ namespace, id })` QQ( 高效SCAN )
-   部分上下文删除: `cache.delete({ namespace, context: { action } })` QQ( 高效SCAN )

**发展工作流程:**

-   **单位测试**数字 : `pnpm test` (20/20通过)
-   **融合测试**数字 : `REDIS_URL=redis://localhost:6379 pnpm test:integration`
-   **原生雷迪斯操作**: 最佳性能使用SCAN + DEL
-   **生产部署**: 使用任何兼容 Redis 服务器的工作

## 常见问题

### @cachehub/redis-cache 是什么？

Overview Redis缓存适配器为 Redis 提供了密接字符串和 TypeCacheKey 支持的缓存库的具体执行\. 这个适配器允许开发者在保持一致性的同时,将Redis作为缓存解决方案来杠杆化

### 如何安装 @cachehub/redis-cache？

在项目目录运行 npm install @cachehub/redis-cache，或使用 pnpm add / yarn add / bun add。

### @cachehub/redis-cache 支持 TypeScript 吗？

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

### @cachehub/redis-cache 支持 ESM 还是 CommonJS？

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

### @cachehub/redis-cache 可以商用吗？

@cachehub/redis-cache 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @cachehub/redis-cache 的下载量有多少？

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

### @cachehub/redis-cache 还在维护吗？

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

