cache.service.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
  2. import { RedisService } from 'nestjs-redis';
  3. @Injectable()
  4. export class CacheService implements OnModuleInit {
  5. public client;
  6. private logger: Logger = new Logger('CacheService');
  7. constructor(private redisService: RedisService) {}
  8. async onModuleInit() {
  9. try {
  10. this.getClient();
  11. this.logger.log('redis init');
  12. } catch (error) {
  13. console.error('error', error);
  14. }
  15. }
  16. async getClient() {
  17. this.client = await this.redisService.getClient();
  18. }
  19. public async set(key: string, value: any, seconds?: number) {
  20. value = JSON.stringify(value);
  21. if (!this.client) {
  22. await this.getClient();
  23. }
  24. if (!seconds) {
  25. await this.client.set(key, value);
  26. } else {
  27. await this.client.set(key, value, 'EX', seconds);
  28. }
  29. }
  30. // rpop
  31. public async rpop(key: string) {
  32. if (!this.client) {
  33. await this.getClient();
  34. }
  35. const data = await this.client.rpop(key);
  36. if (!data) return;
  37. return JSON.parse(data);
  38. }
  39. //获取Range值的方法
  40. public async lpop(key: string) {
  41. if (!this.client) {
  42. await this.getClient();
  43. }
  44. const data = await this.client.lpop(key);
  45. if (!data) return;
  46. return JSON.parse(data);
  47. }
  48. //获取值的方法
  49. public async get(key: string) {
  50. if (!this.client) {
  51. await this.getClient();
  52. }
  53. const data = await this.client.get(key);
  54. if (!data) return;
  55. return JSON.parse(data);
  56. }
  57. public async keys(key: string) {
  58. if (!this.client) {
  59. await this.getClient();
  60. }
  61. const data = await this.client.keys(key);
  62. if (!data) return;
  63. return data;
  64. }
  65. //获取值的方法
  66. public async del(key: string) {
  67. if (!this.client) {
  68. await this.getClient();
  69. }
  70. await this.client.del(key);
  71. }
  72. // 清理缓存
  73. public async flushall(): Promise<any> {
  74. if (!this.client) {
  75. await this.getClient();
  76. }
  77. await this.client.flushall();
  78. }
  79. // publish(channel: string, message: string, callback?: Callback<number>): Pipeline;
  80. public async publish(channel: string, message: string): Promise<any> {
  81. if (!this.client) {
  82. await this.getClient();
  83. }
  84. return await this.client.publish(channel, message);
  85. }
  86. }