UNPKG

@zenweb/cache

Version:
85 lines (84 loc) 2.85 kB
import { Redis, RedisValue } from 'ioredis'; import { SetupOption, SetOption, GetOption, LockGetOption, SetResult, LockOption } from './types.js'; /** * 缓存结果 */ export declare class CacheResult { compressed: boolean; data: Buffer; /** * @param compressed 是否为压缩数据 * @param data 数据 */ constructor(compressed: boolean, data: Buffer); } /** * 对象缓存系统 */ export declare class Cache { redis: Redis; private option; constructor(redis: Redis, option: Required<SetupOption>); /** * 取得缓存剩余有效期 */ ttl(key: string): Promise<number>; /** * 删除缓存 */ del(key: string): Promise<number>; /** * 直接设置缓存 - 不经过序列化的数据 * @param key * @param value * @param ttl 缓存有效时长 (秒),不设置取默认设置 */ setRaw(key: string, value: RedisValue, ttl?: number): Promise<"OK">; /** * 缓存对象 * @param key 缓存key * @param value 缓存值,除了 `Buffer` 以外的值会经过序列化 * @param ttlopt 缓存有效时长 (秒),不设置取默认设置 | 缓存选项 */ set(key: string, value: any, ttlopt?: number | SetOption): Promise<SetResult>; /** * 直接取得缓存 */ getRaw(key: string): Promise<Buffer<ArrayBufferLike> | null>; /** * 取得缓存对象 * @param key 缓存key */ get(key: string, opt: { parse: false; } & GetOption): Promise<CacheResult | undefined>; get<T = unknown>(key: string, opt?: { parse?: true; } & GetOption): Promise<T | undefined>; /** * 取得缓存值,如果缓存不存在则取得锁并调用 fetch 设置缓存值 * - 防止缓存击穿 * - 保障只有一个业务会设置缓存,其他业务会等待设置完成并返回设置结果 * @param key 缓存KEY * @param fetch 缓存设置方法回调 */ lockGet<T = unknown>(key: string, fetch: () => Promise<T> | T, opt: { parse: false; noWait: true; } & LockGetOption): Promise<CacheResult | undefined>; lockGet<T = unknown>(key: string, fetch: () => Promise<T> | T, opt: { noWait: true; } & LockGetOption): Promise<T | undefined>; lockGet<T = unknown>(key: string, fetch: () => Promise<T> | T, opt: { parse: false; } & LockGetOption): Promise<CacheResult>; lockGet<T = unknown>(key: string, fetch: () => Promise<T> | T, opt?: { parse?: true; } & LockGetOption): Promise<T>; /** * 单例执行,在并发情况下保证同一个 key 只会单独执行,防止同时处理 * @param key 锁key * @param run 获得锁时调用 */ singleRunner<T>(key: string, run: () => Promise<T> | T, _opt?: LockOption): Promise<T>; }