卡飞资源网

专业编程技术资源共享平台

Redis:为什么您应该多缓存少查询

还在一次又一次地调用相同的API吗?

这不仅效率低下——而且成本高昂。性能缓慢、成本更高,用户体验更差。

让我们停止这种做法——从这篇文章开始。:D

首先您需要了解Redis,简单来说,它是一个超快速的内存键值存储——非常适合缓存和减少后端负载。

有几种方式可以开始。

如果您正在开发,我建议使用Docker。

为此,您可以在CLI中运行:

docker run -d --name redis-stack-server -p 6379:6379 redis/redis-stack-server:latest

这将启动Redis服务器。但查看实际存储的内容同样重要。为此,使用带有浏览器UI的完整Redis Stack:

docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest

现在,如果您访问
http://localhost:8001/redis-stack/browser

您会找到一个方便的控制面板,可以在其中可视化地存储、浏览和管理您的Redis数据:

要开始,安装redis包:

npm i redis // 或 yarn, npm

现在,让我们设置一些类型和接口来保持代码的整洁和可扩展性。

我们将从一个用于标准化响应的通用枚举开始:

我们的枚举如下:

# generic.interface.ts
export enum StatusEnum {
  SUCCESS = 'success',
  ERROR = 'error'
}

然后,为我们的缓存逻辑定义类型和结构:

# cache.interface.ts
import { StatusEnum } from './generic.interface';

export type CacheCallbackType = Promise<{
  status: StatusEnum;
  data: any;
  error?: any;
}>;

export interface CacheInterface {
  key: string;
  callback: () => CacheCallbackType;
  configs?: {
    expirationInSeconds?: number;
    useUserId?: boolean;
  };
}

interface CacheReturnInterface {
  status: StatusEnum;
  data: any;
}

export type CacheReturnType = Promise<CacheReturnInterface>;

这些接口将帮助保持我们的代码类型化、一致且易于维护,随着项目的增长。

接下来,让我们设置一个辅助类来以整洁和可重用的方式处理Redis操作。

import { createClient } from 'redis';

export default class RedisHelper {
  private static client = createClient({
    username: 'default',
    password: process.env.REDIS_PASSWORD,
    socket: {
      host: process.env.REDIS_URL,
      port: parseInt(process.env.REDIS_PORT)
    }
  });

  static async connect() {
    if (!this.client.isOpen) {
      await this.client.connect();
    }

    return this;
  }

  static async get(key: string) {
    await this.connect();
    const value = await this.client.get(key);

    if (!value) {
      return value;
    }

    return value;
  }

  static async set(
    key: string,
    value: any,
    expirationInSeconds: number = 3600
  ) {
    await this.connect();
    await this.client.json.set(key, '#39;, value);
    await this.client.expire(key, expirationInSeconds);

    return this;
  }

  static async del(key: string) {
    await this.connect();
    await this.client.del(key);
  }

  static async quit() {
    if (this.client.isOpen) {
      await this.client.quit();
    }
  }
}

我们使用Redis的JSON命令(例如.json.set)来更直观地存储结构化数据。这比纯字符串给我们更多的灵活性——特别是在处理嵌套对象或数组时。

有了这个辅助类,我们可以:

  • 仅在需要时连接到Redis(延迟连接)
  • 设置带过期时间的值
  • 轻松获取缓存数据
  • 删除键
  • 优雅地关闭连接

这个辅助类将处理任何类型请求的缓存——只要请求成功。它使用我们创建的RedisHelper与Redis通信。

在我的情况下,我通过将用户ID附加到缓存键来包含基于用户的缓存支持。在您的情况下,请随意调整此逻辑以适应您的需求。

import {
  CacheInterface,
  CacheReturnType
} from '../../interfaces/cache.interface';
import { StatusEnum } from '../../interfaces/generic.interface';
// import getUserId  from '../default/userId';
import RedisHelper from './RedisHelper';

function getUserId () {
   return Math.random(); // 在这里使用您的逻辑!
}

export default class CacheHelper {
  // 检查缓存是否为空
  // 然后运行回调函数
  // 并用结果设置缓存
  static async checkCache({
    key,
    callback,
    configs
  }: CacheInterface): CacheReturnType {
    const cache = await RedisHelper.get(key);
    const expirationInSeconds = configs?.expirationInSeconds || 3600;

    // 仅在configs中指定时才在键中使用userId
    if (configs?.useUserId) {
      const userId = getUserId();
      key = `${key}:${userId}`;
    }

    if (cache) {
      return {
        status: StatusEnum.SUCCESS,
        data: cache
      };
    }

    try {
      const result = await callback();

      if (result.status === StatusEnum.ERROR) {
        return {
          status: StatusEnum.ERROR,
          data: result.data
        };
      }

      await RedisHelper.set(key, result.data, expirationInSeconds);

      return {
        status: StatusEnum.SUCCESS,
        data: result.data
      };
    } catch (error) {
      console.error('Error in checkCache:', error);

      return {
        status: StatusEnum.ERROR,
        data: null
      };
    }
  }

  // 辅助函数,始终在键中使用userId
  static async checkCacheWithId({
    key,
    callback,
    configs
  }: CacheInterface): CacheReturnType {
    return this.checkCache({
      key,
      callback,
      configs: {
        ...configs,
        useUserId: true
      }
    });
  }

  static async deleteCache(
    key: string,
    configs?: {
      useUserId?: boolean;
    }
  ): Promise<void> {
    if (configs?.useUserId) {
      const userId = getUserId();
      key = `${key}:${userId}`;
    }

    if (!key) {
      throw new Error('Key is required to delete cache');
    }

    try {
      await RedisHelper.del(key);
    } catch (error) {
      console.error('Error deleting cache:', error);
      throw error;
    }
  }

  static async deleteUserCache(key: string): Promise<void> {
    return this.deleteCache(key, { useUserId: true });
  }
}

这个实用工具让您完全控制:

  • 从缓存读取
  • 如果需要,写入缓存
  • 处理带或不带用户标识符的缓存键
  • 轻松删除缓存条目

哦,redis中的标签看起来像这样:

movies:user_123
user:123:profile
user:123:posts
user:123:notifications

现在一切都设置好了,使用缓存变得简单而整洁。

以下是如何基于用户ID缓存/categories API请求的示例:

import CacheHelper from './helpers/cache/CacheHelper';
import { StatusEnum } from './interfaces/generic.interface';

api.post('/categories', async (_req, res) => {
  const data = await CacheHelper.checkCacheWithId({
    key: 'categories',
    callback: async (): CacheCallbackType => {
      const data = await Categories();

      if (data.error) {
        return {
          status: StatusEnum.ERROR,
          data: data.error
        };
      }

      return {
        status: StatusEnum.SUCCESS,
        data
      };
    }
  });

  if (data.status === StatusEnum.ERROR) {
    return res.status(500).send({ error: data.data });
  }

  return res.status(200).send(data.data);
});

这里发生了什么?

  • checkCacheWithId检查是否已经为该特定用户缓存了响应版本。
  • 如果没有缓存,它运行回调(Categories()),保存结果并返回。
  • 如果回调中有错误,它不会被缓存——而是返回错误。
  • 结果快速而整洁地返回给客户端。

想要更进一步?您可以将此抽象为中间件或使用装饰器(如果您正在使用像NestJS这样的框架)。

如果您需要下一步的帮助,请告诉我!


控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言