| 1 | import NodeCache from 'node-cache'; |
| 2 | |
| 3 | class Cache { |
| 4 | private static instance: Cache; |
| 5 | private cache: NodeCache; |
| 6 | |
| 7 | private constructor() { |
| 8 | this.cache = new NodeCache(); |
| 9 | } |
| 10 | |
| 11 | public static getInstance(): Cache { |
| 12 | if (!Cache.instance) Cache.instance = new Cache(); |
| 13 | return Cache.instance; |
| 14 | } |
| 15 | |
| 16 | /** |
| 17 | * 缓存数据 |
| 18 | * @param key 缓存key |
| 19 | * @param value 缓存值 |
| 20 | * @param ttl 缓存时间 秒 |
| 21 | */ |
| 22 | public setCache(key: string, value: any, ttl?: number) { |
| 23 | if (ttl) { |
| 24 | this.cache.set(key, value, ttl); |
| 25 | } else { |
| 26 | this.cache.set(key, value); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | public getCache(key: string) { |
| 31 | return this.cache.get(key); |
| 32 | } |
| 33 | |
| 34 | public delCache(key: string) { |
| 35 | return this.cache.del(key); |
| 36 | } |
| 37 | |
| 38 | public clearCache() { |
| 39 | return this.cache.flushAll(); |
| 40 | } |
| 41 | |
| 42 | // 更改TTL |
| 43 | public updateCacheTTL(key: string, ttl: number) { |
| 44 | this.cache.ttl(key, ttl); |
| 45 | } |
| 46 | |
| 47 | // 设置多个缓存 |
| 48 | public setMultiCache(list: { key: string; val: any; ttl?: number }[]) { |
| 49 | this.cache.mset(list); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | export const GlobleCache = Cache.getInstance(); |
| 54 |