GlobalCache.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import EventEmitter from 'events';
  2. /**
  3. * 全局缓存类
  4. * 使用单例模式实现的带过期时间的键值对存储
  5. */
  6. class GlobalCache extends EventEmitter {
  7. constructor() {
  8. super();
  9. if (GlobalCache.instance) {
  10. return GlobalCache.instance;
  11. }
  12. // 存储数据的 Map
  13. this.cache = new Map();
  14. // 存储定时器的 Map
  15. this.timers = new Map();
  16. GlobalCache.instance = this;
  17. }
  18. /**
  19. * 设置缓存值
  20. * @param {string} key - 键
  21. * @param {*} value - 值
  22. * @param {number} [expireTime=0] - 过期时间(秒),0表示永不过期
  23. * @returns {*} 设置的值
  24. */
  25. set(key, value, expireTime = 0) {
  26. if (typeof key !== 'string') {
  27. throw new Error('Key must be a string');
  28. }
  29. // 如果该key已存在,清除之前的定时器
  30. if (this.timers.has(key)) {
  31. clearTimeout(this.timers.get(key));
  32. this.timers.delete(key);
  33. }
  34. // 存储值
  35. this.cache.set(key, value);
  36. // 如果设置了过期时间
  37. if (expireTime > 0) {
  38. const timer = setTimeout(() => {
  39. this.delete(key);
  40. this.emit('expired', key); // 触发过期事件
  41. }, expireTime * 1000);
  42. // 存储定时器
  43. this.timers.set(key, timer);
  44. }
  45. return value;
  46. }
  47. /**
  48. * 获取缓存值
  49. * @param {string} key - 键
  50. * @returns {*} 值,如果不存在或已过期返回null
  51. */
  52. get(key) {
  53. if (typeof key !== 'string') {
  54. throw new Error('Key must be a string');
  55. }
  56. return this.cache.has(key) ? this.cache.get(key) : 0;
  57. }
  58. /**
  59. * 删除缓存值
  60. * @param {string} key - 键
  61. * @returns {boolean} 是否成功删除
  62. */
  63. delete(key) {
  64. if (this.timers.has(key)) {
  65. clearTimeout(this.timers.get(key));
  66. this.timers.delete(key);
  67. }
  68. return this.cache.delete(key);
  69. }
  70. /**
  71. * 清除所有缓存
  72. */
  73. clear() {
  74. // 清除所有定时器
  75. for (const timer of this.timers.values()) {
  76. clearTimeout(timer);
  77. }
  78. this.timers.clear();
  79. this.cache.clear();
  80. }
  81. /**
  82. * 获取所有缓存的键
  83. * @returns {string[]} 键数组
  84. */
  85. keys() {
  86. return Array.from(this.cache.keys());
  87. }
  88. /**
  89. * 获取缓存数量
  90. * @returns {number} 缓存数量
  91. */
  92. size() {
  93. return this.cache.size;
  94. }
  95. /**
  96. * 检查键是否存在
  97. * @param {string} key - 键
  98. * @returns {boolean} 是否存在
  99. */
  100. has(key) {
  101. return this.cache.has(key);
  102. }
  103. }
  104. // 导出单例实例
  105. export const globalCache = new GlobalCache();