@ geekmidas/ cache (笑声)
一个用于TypeScript应用程序的型式安全而灵活的缓存库,支持多个缓存执行和统一的接口.
特征
- 类型安全: 完全类型Script支持,并带有用于强类型的缓存值的通用软件
- 统一接口页:1
Cache<T>所有执行的接口 - 多个后端: 内存、Redis(Upstash)、博览会安全存储和基于文件的执行
- 自动同步 API: 基于承诺的接口,促进各执行工作的一致性
- 弹性 TTL:支持在所有执行中实现实时
- 简单测试: 简单的接口使嘲笑和测试变得简单明了
- 模块导出: 只导入您需要的东西
- 反应原生支持: Expo Security Store 用于移动应用程序的操作
安装
npm install @geekmidas/cache
可选的依赖关系
通过 Upstash 支持 Redis :
npm install @upstash/redis
通过 Expo 反应本地支持 :
npm install expo-secure-store
基于文件的缓存自动包含所有需要的依赖.
快速启动
记忆缓存
适合开发、测试或简单的应用:
import { InMemoryCache } from '@geekmidas/cache/memory';
const cache = new InMemoryCache<string>();
// Set a value
await cache.set('user:123', 'John Doe');
// Get a value
const userName = await cache.get('user:123'); // 'John Doe'
// Delete a value
await cache.delete('user:123');
// Check if value exists
const exists = await cache.get('user:123'); // undefined
Redis 缓存( Upstash)
生产应用需要分布式缓存:
import { UpstashCache } from '@geekmidas/cache/upstash';
const cache = new UpstashCache<User>(
process.env.UPSTASH_REDIS_URL!,
process.env.UPSTASH_REDIS_TOKEN!
);
// Set with TTL (1 hour)
await cache.set('user:123', { id: 123, name: 'John Doe' }, 3600);
// Get typed object
const user = await cache.get('user:123'); // User | undefined
// Delete
await cache.delete('user:123');
文件缓存
持久基于文件的缓存用于CLI工具并构建系统. 数据作为JSON存储在磁盘上,幸存进程重新启动:
import { FileCache } from '@geekmidas/cache/file';
// Default path: process.cwd()/.gkm/cache.json
const cache = new FileCache();
// Custom path and TTL
const cache = new FileCache({
path: '/tmp/my-app/cache.json',
ttl: 3600, // 1 hour default TTL
});
// Set a value with TTL (in seconds)
await cache.set('build:hash', 'abc123', 300);
// Get a value
const hash = await cache.get('build:hash'); // string | undefined
// Check remaining TTL
const remaining = await cache.ttl('build:hash'); // seconds
// Delete a value
await cache.delete('build:hash');
API 参考
缓存接口
所有缓存执行都遵循此接口 :
interface Cache<T> {
get(key: string): Promise<T | undefined>;
set(key: string, value: T, ttl?: number): Promise<void>;
delete(key: string): Promise<void>;
}
方法
get(key: string): Promise<T | undefined>
从缓存中获取一个值.
- 参数数字 :
key- 缓存钥匙 - 回返: 承诺解析缓存值或
undefined如果找不到的话 - 示例数字 :
const value = await cache.get('my-key'); if (value !== undefined) { // Use the value }
set(key: string, value: T, ttl?: number): Promise<void>
在缓存中存储一个值.
- 参数数字 :
key- 缓存钥匙value- 存储值ttl- 可选时间- 数秒
- 回返: 承诺在操作结束后解决
- 示例数字 :
// Set without TTL await cache.set('key', 'value'); // Set with 1 hour TTL await cache.set('key', 'value', 3600);
delete(key: string): Promise<void>
删除缓存中的值.
- 参数数字 :
key- 要删除的缓存密钥 - 回返: 承诺在操作结束后解决
- 示例数字 :
await cache.delete('my-key');
记忆缓存
简单的内存缓存执行 .
import { InMemoryCache } from '@geekmidas/cache/memory';
class InMemoryCache<T> implements Cache<T>
特征
- QQ 快速访问( 无网络间隔)
- QQ 对对象的引用平等
- * 没有外部依赖关系
- QQ 没有 TTL 支持( TTL 参数被忽略)
- 程序重新启动时丢失的数据
- 不适合多功能应用程序
示例
const cache = new InMemoryCache<number>();
await cache.set('counter', 42);
const count = await cache.get('counter'); // 42
向上缓存
基于 Redis 的缓存使用 Upstash Redis 客户端.
import { UpstashCache } from '@geekmidas/cache/upstash';
class UpstashCache<T> implements Cache<T>
构造器
new UpstashCache<T>(url: string, token: string)
url: Upstash Redis URL 页面存档备份,存于互联网档案馆token: Upstash Redis 符号
特征
- 持续储存
- TTL 支持( 默认为 3600 秒)
- 分配缓存
- JSON 序列化/去序化
- QQ 需要外部 Redis 服务
- 业务的网络延迟性
示例
interface User {
id: number;
name: string;
email: string;
}
const cache = new UpstashCache<User>(
'https://your-redis-url.upstash.io',
'your-token'
);
await cache.set('user:1', {
id: 1,
name: 'John Doe',
email: '[email protected]'
}, 7200); // 2 hours TTL
const user = await cache.get('user:1');
文件缓存
基于文件的持续缓存,将条目作为JSON存储在磁盘上.
import { FileCache } from '@geekmidas/cache/file';
class FileCache implements Cache
构造器
new FileCache(options?: FileCacheOptions)
path: 缓存 JSON 文件的路径( 默认 ):process.cwd()/.gkm/cache.json(中文(简体) )ttl: 以秒计的默认 TTL( 默认 ):600(中文(简体) )
特征
- * 整个进程持续存储重新启动
- 自动过期的 TTL 支持
- QQ 安全并发写( 在进程 mutex + 跨进程文件锁定)
- QQ 自动创建父目录
- * 不需要外部服务
- 不适合高通量应用程序
- 不适合多机分布式缓冲
示例
const cache = new FileCache({ path: '/tmp/app-cache.json', ttl: 3600 });
await cache.set('config', { theme: 'dark' });
const config = await cache.get('config'); // { theme: 'dark' }
const remaining = await cache.ttl('config'); // ~3600
曝光安全缓存
使用 Expo SecurityStore 安全存储 React 本地应用程序 .
import { ExpoSecureCache } from '@geekmidas/cache/expo';
class ExpoSecureCache<T> implements Cache<T>
特征
- 设备上的加密安全存储
- 自动过期的 TTL 支持
- QQ 持续跨应用程序重启
- & Android Keystore 备份
- QQ 只执行本地/ 执行
- * 储存能力有限(按平台排列)
- QQ 慢于记忆缓存
示例
import { ExpoSecureCache } from '@geekmidas/cache/expo';
interface AuthTokens {
accessToken: string;
refreshToken: string;
}
const cache = new ExpoSecureCache<AuthTokens>();
// Store tokens securely with 1 hour TTL
await cache.set('auth:tokens', {
accessToken: 'eyJhbGciOiJIUzI1NiIs...',
refreshToken: 'dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4...'
}, 3600);
// Retrieve tokens
const tokens = await cache.get('auth:tokens');
// Clear tokens on logout
await cache.delete('auth:tokens');
平台考虑因素
- iOS系统: 使用 keychain 服务, 数据在应用程序的再安装中持续使用
- 机器人: 使用Android Keystore, 解析应用软件上的数据
- 存储限制: 多数设备每件约2KB
- 业绩: Async 操作比内存缓存慢
高级使用
类型安全
缓存与 TypeScript 通用软件完全类型安全 :
// String cache
const stringCache = new InMemoryCache<string>();
await stringCache.set('key', 'value');
const str: string | undefined = await stringCache.get('key');
// Object cache
interface Product {
id: number;
name: string;
price: number;
}
const productCache = new InMemoryCache<Product>();
await productCache.set('product:1', { id: 1, name: 'Widget', price: 9.99 });
const product: Product | undefined = await productCache.get('product:1');
缓存摘要
创建缓存不可知性服务 :
interface UserService {
getUser(id: number): Promise<User | undefined>;
setUser(user: User): Promise<void>;
deleteUser(id: number): Promise<void>;
}
class CachedUserService implements UserService {
constructor(
private cache: Cache<User>,
private userRepository: UserRepository
) {}
async getUser(id: number): Promise<User | undefined> {
const cacheKey = `user:${id}`;
// Try cache first
let user = await this.cache.get(cacheKey);
if (user) return user;
// Fallback to repository
user = await this.userRepository.findById(id);
if (user) {
await this.cache.set(cacheKey, user, 3600); // 1 hour
}
return user;
}
async setUser(user: User): Promise<void> {
await this.userRepository.save(user);
await this.cache.set(`user:${user.id}`, user, 3600);
}
async deleteUser(id: number): Promise<void> {
await this.userRepository.delete(id);
await this.cache.delete(`user:${id}`);
}
}
// Use with any cache implementation
const service = new CachedUserService(
new InMemoryCache<User>(), // or new UpstashCache<User>(url, token)
new UserRepository()
);
工厂模式
基于配置创建缓存实例 :
interface CacheConfig {
type: 'memory' | 'redis' | 'file' | 'expo';
redis?: {
url: string;
token: string;
};
file?: {
path?: string;
ttl?: number;
};
}
function createCache<T>(config: CacheConfig): Cache<T> {
switch (config.type) {
case 'memory':
return new InMemoryCache<T>();
case 'redis':
if (!config.redis) throw new Error('Redis config required');
return new UpstashCache<T>(config.redis.url, config.redis.token);
case 'file':
return new FileCache(config.file);
case 'expo':
return new ExpoSecureCache<T>();
default:
throw new Error(`Unsupported cache type: ${config.type}`);
}
}
const cache = createCache<User>({
type: process.env.NODE_ENV === 'production' ? 'redis' : 'memory',
redis: {
url: process.env.UPSTASH_REDIS_URL!,
token: process.env.UPSTASH_REDIS_TOKEN!,
},
});
包装图案
添加日志或度量衡等功能 :
class LoggingCache<T> implements Cache<T> {
constructor(
private cache: Cache<T>,
private logger: Logger
) {}
async get(key: string): Promise<T | undefined> {
this.logger.debug(`Cache GET: ${key}`);
const value = await this.cache.get(key);
this.logger.debug(`Cache GET result: ${value ? 'HIT' : 'MISS'}`);
return value;
}
async set(key: string, value: T, ttl?: number): Promise<void> {
this.logger.debug(`Cache SET: ${key} (TTL: ${ttl})`);
await this.cache.set(key, value, ttl);
}
async delete(key: string): Promise<void> {
this.logger.debug(`Cache DELETE: ${key}`);
await this.cache.delete(key);
}
}
const cache = new LoggingCache(
new UpstashCache<User>(url, token),
logger
);
测试
嘲笑
界面使测试变得容易:
import { Cache } from '@geekmidas/cache';
class MockCache<T> implements Cache<T> {
private store = new Map<string, T>();
async get(key: string): Promise<T | undefined> {
return this.store.get(key);
}
async set(key: string, value: T): Promise<void> {
this.store.set(key, value);
}
async delete(key: string): Promise<void> {
this.store.delete(key);
}
}
// Use in tests
const mockCache = new MockCache<User>();
const service = new CachedUserService(mockCache, mockRepository);
用真实执行进行测试
import { InMemoryCache } from '@geekmidas/cache/memory';
describe('UserService', () => {
let cache: Cache<User>;
let service: CachedUserService;
beforeEach(() => {
cache = new InMemoryCache<User>();
service = new CachedUserService(cache, mockRepository);
});
it('should cache user data', async () => {
const user = { id: 1, name: 'John' };
await service.setUser(user);
const cachedUser = await cache.get('user:1');
expect(cachedUser).toEqual(user);
});
});
业绩考量
记忆缓存
- 专业:非常快,没有网络间隔
- 计数: 受到现有内存的限制,不是持久性的
- 最好还是: 开发,测试,单机应用
向上缓存
- 专业: 持久性、分布性、可伸缩性
- 计数:网络延迟、外部依赖
- 最好还是: 生产,多智能应用程序,共享缓存
文件缓存
- 专业: 持续、无外部服务、跨流程安全
- 计数:磁盘 I/O 延迟,不适合高吞吐量
- 最好还是: CLI 工具,构建系统,本地开发缓存
曝光安全缓存
- 专业: 安全、加密、在设备上坚持
- 计数: 只反应原生, 存储限制, 操作较慢
- 最好还是: 移动应用程序,敏感数据(文件夹,证书)
关键战略
- 使用适当的 TTL: 缓存新鲜度和性能之间的平衡
- 考虑缓存大小: 监视内存缓存的使用情况
- 执行倒计时: 当缓存不可用时, 总是有一个倒计时
- 使用压缩:对于大型对象,在缓存前考虑压缩
处理错误
缓存操作可能失败, 因此执行正确的错误处理 :
async function getUserSafely(id: number): Promise<User | undefined> {
try {
const cached = await cache.get(`user:${id}`);
if (cached) return cached;
} catch (error) {
console.warn('Cache get failed, falling back to database:', error);
}
try {
const user = await database.getUser(id);
if (user) {
try {
await cache.set(`user:${id}`, user, 3600);
} catch (error) {
console.warn('Cache set failed:', error);
}
}
return user;
} catch (error) {
console.error('Database query failed:', error);
throw error;
}
}
移徙指南
从地图到缓存
// Old way
const cache = new Map<string, User>();
cache.set('user:1', user);
const user = cache.get('user:1');
// New way
const cache = new InMemoryCache<User>();
await cache.set('user:1', user);
const user = await cache.get('user:1');
从其它缓存库
多数缓存库可被修改以实施 Cache<T> 接口 :
class RedisCache<T> implements Cache<T> {
constructor(private redis: RedisClient) {}
async get(key: string): Promise<T | undefined> {
const value = await this.redis.get(key);
return value ? JSON.parse(value) : undefined;
}
async set(key: string, value: T, ttl?: number): Promise<void> {
const serialized = JSON.stringify(value);
if (ttl) {
await this.redis.setex(key, ttl, serialized);
} else {
await this.redis.set(key, serialized);
}
}
async delete(key: string): Promise<void> {
await this.redis.del(key);
}
}
捐款
- 遵循现有的代码样式(2个空格,单引号,分号)
- 添加新特性的综合测试
- 确保所有执行都遵循
Cache<T>接口 - 更新 API 更改的文档
- 使用“ 单位合并” 测试哲学
许可证
麻省理工学院执照 - 详情见LICENSE文件.