Redis 快取适应器
概览
Redis缓存适配器提供了专为Redis提供的缓存库的实现,并附有混合字符串和TypeCacheKey支持. 这个适配器允许开发者利用Redis作为缓存解决方案,同时在不同的缓存执行间保持一致的API.
福利
- 无缝一体化:在不更改应用程序代码的情况下,将Redis缓存方便地整合到您的应用程序中.
- 动态配置: 配置缓存适配器,使用环境变量在不同的缓存策略之间切换.
- 一般支助: 存储并取回复杂对象,同时通过通用类型支持维护类型安全.
- 混合密钥支持: 支持字符串密钥和结构化的 TypeCacheKey 对象用于高级缓存管理.
- 原生模式删除: 使用 Redis SCAN + DEL 操作按模式删除多个缓存条目.
- 即时一致性: 所有操作都使用本地Redis命令提供即时一致性.
安装
要使用 Redis 缓存适配器, 请使用以下命令安装软件包 :
pnpm add @cachehub/redis-cache
配置
要配置 Redis 缓存适配器,请在应用程序中设置以下环境变量:
CACHE_TYPE: 设定为redis来使用 Redis 缓存适配器.CACHE_REDIS_URL: Redis 服务器的 URL.
使用量
要在您的应用程序中使用 Redis 缓存适配器, 请遵循这些步骤 :
- 导入 Redis 缓存包, 以注册到工厂 。 例如:
import '@cachehub/redis-cache'; - 使用工厂创建缓存实例 .
- 使用缓存实例设置、获取、删除并检查缓存条目.
示例
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: '[email protected]'
};
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 用法
适配器支持高级情景的结构缓存密钥 :
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 操作进行即时一致性:
支持全部删除模式 :
// 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: 配置的环境变量.
捐款
欢迎捐款! 随意叉出这个寄存器并提交拉取请求. 在提交之前,请确保您的代码通过所有起伏和单元测试.
您可以使用 :
pnpm format
您可以使用 :
pnpm test
您可以使用 :
# 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. 单位测试(快速 -- -- 不要求重复)
pnpm test
- 用被嘲笑的Redis客户端运行所有单位测试
- 测试 TypeCacheKey 功能、序列化和图案删除
- 以秒计完成
2. 综合试验(Reders Redis)
# 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
发展 工作流量
设置和建筑
# Install dependencies
pnpm install
# Build the package
pnpm build
# Check TypeScript compilation
pnpm check
# Format code
pnpm format
完成测试工作流程
# 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 服务器的工作