2
0

redis.util.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { createClient, RedisClientType } from 'redis';
  2. class RedisUtil {
  3. private client: RedisClientType | null = null;
  4. private static instance: RedisUtil;
  5. private constructor() {}
  6. public static getInstance(): RedisUtil {
  7. if (!RedisUtil.instance) {
  8. RedisUtil.instance = new RedisUtil();
  9. }
  10. return RedisUtil.instance;
  11. }
  12. async connect(): Promise<RedisClientType> {
  13. if (!this.client) {
  14. this.client = createClient({
  15. url: process.env.REDIS_URL || 'redis://127.0.0.1:6379'
  16. });
  17. this.client.on('error', (err) => {
  18. console.error('Redis Client Error:', err);
  19. });
  20. await this.client.connect();
  21. }
  22. return this.client;
  23. }
  24. async disconnect(): Promise<void> {
  25. if (this.client) {
  26. await this.client.disconnect();
  27. this.client = null;
  28. }
  29. }
  30. async setSessionKey(userId: number, sessionKey: string, ttlSeconds: number = 7200): Promise<void> {
  31. const client = await this.connect();
  32. const key = `session_key:${userId}`;
  33. await client.set(key, sessionKey, {
  34. EX: ttlSeconds // 默认2小时过期,与微信session_key有效期一致
  35. });
  36. }
  37. async getSessionKey(userId: number): Promise<string | null> {
  38. const client = await this.connect();
  39. const key = `session_key:${userId}`;
  40. return await client.get(key);
  41. }
  42. async deleteSessionKey(userId: number): Promise<void> {
  43. const client = await this.connect();
  44. const key = `session_key:${userId}`;
  45. await client.del(key);
  46. }
  47. async isSessionKeyValid(userId: number): Promise<boolean> {
  48. const sessionKey = await this.getSessionKey(userId);
  49. return !!sessionKey;
  50. }
  51. }
  52. export const redisUtil = RedisUtil.getInstance();