# @happyvertical/cache 中文文档

规范地址：https://npmcn.com/package/%40happyvertical/cache/

版本：0\.113\.1
npm 元数据更新时间：2026-11-17T00:01:02.104Z
中文译文更新时间：2026-11-17T10:44:08.571Z
软件包许可：ISC

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

原始 npm 页面：https://www.npmjs.com/package/%40happyvertical/cache
原文对照：https://npmcn.com/package/%40happyvertical/cache/?lang=original
项目主页：https://github.com/happyvertical/sdk/tree/main/packages/cache#readme
源码仓库：https://github.com/happyvertical/sdk

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

- 包体积（解压后）：193 kB，33 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：4 个
- 首次发布：2026-06-23T08:14:11.312Z
- 最新版本发布：2026-11-17T00:01:01.743Z
- 近 30 天下载量：11375（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：132（近 12 个月 132 个）

## 中文简介

支持内存、文件和 Redis 后端的标准化缓存接口

## 安装

```sh
npm install @happyvertical/cache
```

也可以使用：`pnpm add @happyvertical/cache`、`yarn add @happyvertical/cache`、`bun add @happyvertical/cache`

## README

# @ happyvertical/ cache (笑) (笑) (掌声)

统一缓存接口支持内存,文件,Redis,以及带有TTL的S3后端,驱逐政策,批量操作,并压缩. 所有供应商执行相同的 `CacheProvider` 接口,因此可以在不更改应用程序代码的情况下互换后端.

## 安装

```bash
pnpm add @happyvertical/cache
# Requires @happyvertical/utils as a peer
# redis and @aws-sdk/client-s3 are bundled
```

## 快速启动

```typescript
import { getCache } from '@happyvertical/cache';

const cache = await getCache({
  provider: 'memory',
  maxSize: 100 * 1024 * 1024,
  evictionPolicy: 'lru',
});

await cache.set('user:123', { name: 'Alice' }, 3600); // TTL in seconds
const user = await cache.get('user:123');
await cache.delete('user:123');
await cache.close();
```

## 供应商

### 内存

进行中 `Map`\- 基于缓存。 无外相依. 重新启动时丢失数据 .

```typescript
const cache = await getCache({
  provider: 'memory',
  namespace: 'app',
  defaultTTL: 3600,          // seconds
  maxSize: 100 * 1024 * 1024, // bytes (default 100MB)
  maxEntries: 10000,          // default 10k
  evictionPolicy: 'lru',      // 'lru' | 'lfu' | 'fifo'
  checkPeriod: 60000,          // expiration sweep interval in ms
});
```

### 文件

以可选的 gzip 压缩将条目存储为磁盘上的文件 。 坚持到重启为止.

```typescript
const cache = await getCache({
  provider: 'file',
  cacheDir: './cache',         // required
  compression: true,           // gzip (default false)
  maxSize: 500 * 1024 * 1024,  // bytes (default 500MB)
  fileExtension: '.cache',
  checkPeriod: 300000,         // cleanup interval in ms
});
```

### 重写

使用 `redis` npm客户端. 支持大值的可选gzip压缩.

```typescript
const cache = await getCache({
  provider: 'redis',
  host: 'localhost',
  port: 6379,
  password: 'secret',
  db: 0,
  namespace: 'app',
  enableCompression: true,
  compressionThreshold: 1024, // bytes — only compress values larger than this
  connectTimeout: 5000,       // ms
});
```

### 第3条

将条目存储为 S3 对象 。 对运行之间必须持续的 CI 缓存有用 。 默认启用了压缩以减少相继成本 .

```typescript
const cache = await getCache({
  provider: 's3',
  bucket: 'my-cache-bucket',
  prefix: 'cache/',
  region: 'us-east-1',
  compression: true,           // default true
  compressionThreshold: 1024,  // bytes
});
```

## API 密码

所有提供者执行 `CacheProvider`数字 :

```typescript
interface CacheProvider {
  get<T>(key: string): Promise<T | undefined>;
  set<T>(key: string, value: T, ttl?: number): Promise<void>;
  has(key: string): Promise<boolean>;
  delete(key: string): Promise<boolean>;
  clear(namespace?: string): Promise<void>;
  keys(pattern?: string): Promise<string[]>;
  getMany<T>(keys: string[]): Promise<Map<string, T>>;
  setMany<T>(entries: Array<{ key: string; value: T; ttl?: number }>): Promise<void>;
  deleteMany(keys: string[]): Promise<number>;
  touch(key: string, ttl: number): Promise<boolean>;
  getStats(): Promise<CacheStats>;
  close(): Promise<void>;
}
```

-   **TTL 电话** 总是数秒。 关闭不过期.
-   **`keys()`** 接受 glob 模式 (`user:*`, (中文(简体) ), `report:2024*`) (中文(简体) ).
-   **`touch()`** 更新 TTL 不修改值。 回返 `false` 如果钥匙不存在的话.
-   **批量操作** (单位:千美元)`getMany`, (中文(简体) ), `setMany`, (中文(简体) ), `deleteMany`)减少来回行走,尤其是为Redis.

## 环境变量

配置可以从 `HAVE_CACHE_*` 环境变量通过 `@happyvertical/utils/loadEnvConfig`方案选项总是优先.

| 变量 | 地图到 | 页:1 |
| --- | --- | --- |
| `HAVE_CACHE_PROVIDER` | `provider` | `memory`, (中文(简体) ), `file`, (中文(简体) ), `redis`, (中文(简体) ), `s3` |
| `HAVE_CACHE_NAMESPACE` | `namespace` |  |
| `HAVE_CACHE_DEFAULT_TTL` | `defaultTTL` | 秒数 |
| `HAVE_CACHE_MAX_SIZE` | `maxSize` | 字节( 记忆/ 文件) |
| `HAVE_CACHE_MAX_ENTRIES` | `maxEntries` | 仅包含 |
| `HAVE_CACHE_EVICTION_POLICY` | `evictionPolicy` | 仅包含 |
| `HAVE_CACHE_CACHE_DIR` | `cacheDir` | 仅文件 |
| `HAVE_CACHE_COMPRESSION` | `compression` | 文件/s3 |
| `HAVE_CACHE_HOST` | `host` | 仅重新编号 |
| `HAVE_CACHE_PORT` | `port` | 仅重新编号 |
| `HAVE_CACHE_PASSWORD` | `password` | 仅重新编号 |
| `HAVE_CACHE_BUCKET` | `bucket` | s3 仅限 |
| `HAVE_CACHE_PREFIX` | `prefix` | s3 仅限 |
| `HAVE_CACHE_REGION` | `region` | s3 仅限 |

## 错误分类

所有错误延伸 `CacheError(message, code, provider)`数字 :

-   `CacheKeyError` — 无效的密钥( 空或 > 250字符)
-   `CacheConnectionError` ——后端无法接通(Redis)
-   `CacheSizeError` - 输入将超过 `maxSize`
-   `CacheSerializationError` - JSON 序列化/去序列化失败

## 出口公用事业

低级帮助者从 `shared/utils`数字 :

-   `isValidKey(key)` 检查密钥长度限制
-   `calculateSize(value)` 大约JSON字节大小
-   `matchesPattern(pattern, str)` - 格布比对
-   `formatKey(namespace, key)` 编号 : `extractKey(namespace, fullKey)` 命名空间前缀
-   `isExpired(expiresAt)` 编号 : `calculateExpiration(ttl)` - TTL 数学
-   `serialize(value)` 编号 : `deserialize(json)` - JSON包装器

## 常见问题

### @happyvertical/cache 是什么？

支持内存、文件和 Redis 后端的标准化缓存接口

### 如何安装 @happyvertical/cache？

在项目目录运行 npm install @happyvertical/cache，或使用 pnpm add / yarn add / bun add。它还提供命令行工具 have-cache-context，可以用 npx have-cache-context 直接运行。

### @happyvertical/cache 支持 TypeScript 吗？

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

### @happyvertical/cache 支持 ESM 还是 CommonJS？

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

### @happyvertical/cache 可以商用吗？

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

### @happyvertical/cache 的下载量有多少？

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

### @happyvertical/cache 还在维护吗？

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

