/* * @author wuweiru * @date 2020/11/05 15:03 */ import Redis, { KeyType, ValueType } from 'ioredis'; type RedisOptions = { databaseIndex: number; host: string; port: number; }; export class RedisClient { private readonly client: Redis.Redis; private readonly options: RedisOptions; private static instance?: RedisClient; constructor(options: RedisOptions) { this.options = options; this.client = new Redis({ port: this.options.port, host: this.options.host, db: this.options.databaseIndex }); } static getInstance() { RedisClient.instance ??= new RedisClient({ port: parseInt(`${process.env.REDIS_PORT}`, 0), host: `${process.env.REDIS_HOST}`, databaseIndex: parseInt(`${process.env.REDIS_CACHE_DB}`, 0) }); return RedisClient.instance; } async set(key: KeyType, value: ValueType): Promise { await this.client.set(key, value); } async setExpire(params: { key: KeyType; value: ValueType; time: number; }): Promise { await this.client.set(params.key, params.value, 'EX', params.time); } async get(key: KeyType): Promise { const result = await this.client.get(key); return result; } async delete(key: KeyType): Promise { const result = await this.client.del(key); return result; } async getList(keyList: KeyType[]): Promise> { const result = await this.client.mget(keyList); return result; } async setList( keyValueList: { key: string; value: string }[] ): Promise<[Error | null, any][]> { const setCommands = keyValueList.map(item => ['set', item.key, item.value]); const result = await this.client.multi(setCommands).exec(); return result; } async setExpireList( keyValueList: { key: string; value: string; time: string }[] ): Promise<[Error | null, any][]> { const setCommands = keyValueList.map(item => [ 'set', item.key, item.value, 'EX', item.time ]); const result = await this.client.multi(setCommands).exec(); return result; } async deleteList(keyList: string[]): Promise<[Error | null, any][]> { const deleteCommands = keyList.map(item => ['del', item]); const result = await this.client.multi(deleteCommands).exec(); return result; } }