| 1 | import { Injectable } from '@nestjs/common' |
| 2 | import { Redis } from 'ioredis' |
| 3 | |
| 4 | @Injectable() |
| 5 | export class RedisService { |
| 6 | constructor(private readonly client: Redis) { } |
| 7 | |
| 8 | /** |
| 9 | * 设置key-value |
| 10 | */ |
| 11 | async set(key: string, value: string, seconds?: number): Promise<boolean> { |
| 12 | if (!seconds) |
| 13 | return (await this.client.set(key, value)) === 'OK' |
| 14 | |
| 15 | return (await this.client.set(key, value, 'EX', seconds)) === 'OK' |
| 16 | } |
| 17 | |
| 18 | async setNx(key: string, value: string, seconds?: number): Promise<boolean> { |
| 19 | if (!seconds) |
| 20 | return (await this.client.set(key, value, 'NX')) === 'OK' |
| 21 | |
| 22 | return (await this.client.set(key, value, 'EX', seconds, 'NX')) === 'OK' |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * 设置 json key-value |
| 27 | */ |
| 28 | async setJson<T>(key: string, value: T, seconds?: number): Promise<boolean> { |
| 29 | return this.set(key, JSON.stringify(value), seconds) |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * 获取值 |
| 34 | */ |
| 35 | async get(key: string) { |
| 36 | return await this.client.get(key) |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * 获取 json 值 |
| 41 | */ |
| 42 | async getJson<T>(key: string): Promise<T | null> { |
| 43 | const value = await this.get(key) |
| 44 | return value ? JSON.parse(value) : null |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * 清除值 |
| 49 | */ |
| 50 | async del(key: string): Promise<boolean> { |
| 51 | const data = await this.client.del(key) |
| 52 | return !!data |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * 设置过期时间 |
| 57 | */ |
| 58 | async expire(key: string, times = 0): Promise<boolean> { |
| 59 | const data = await this.client.pexpire(key, times) |
| 60 | return data === 1 |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * 获取剩余时间 (秒) |
| 65 | */ |
| 66 | async ttl(key: string): Promise<number> { |
| 67 | const data = await this.client.pttl(key) |
| 68 | return data |
| 69 | } |
| 70 | |
| 71 | async eval(...args: [ |
| 72 | script: string | Buffer, |
| 73 | numkeys: number | string, |
| 74 | ...args: (string | Buffer | number)[], |
| 75 | ]) { |
| 76 | return this.client.eval(...args) |
| 77 | } |
| 78 | |
| 79 | async rename(oldKey: string, newKey: string): Promise<boolean> { |
| 80 | const result = await this.client.rename(oldKey, newKey) |
| 81 | return result === 'OK' |
| 82 | } |
| 83 | } |
| 84 |