插桩缓存

了解如何手动插桩代码以使用 Sentry 的 Cache 模块。

缓存可以用于加速数据检索,从而提高应用程序性能。因为应用程序将从内存中获取数据(在最佳情况下),而不是从潜在较慢的数据层获取数据。缓存可以加速读取密集型的工作负载,例如问答门户、游戏、媒体分享和社交网络。

Sentry 提供了一个 缓存监控仪表板,可以使用 Sentry 的 Redis 集成进行自动插桩(更多功能即将推出)。

如果你使用 ioredisredis 等 Redis 客户端来缓存数据,需要在 redisIntegration 选项中指定 cachePrefixes。此配置允许 Sentry 将具有定义前缀的键访问分类为“缓存操作”。

Copied
Sentry.init({
  integrations: [
    redisIntegration({
      cachePrefixes: ["posts:", "authors:"],
    }),
  ],
});

如果你使用的是 Sentry 的 Redis 集成之外的其他工具,你需要按照以下步骤手动插桩 Cache 模块

你需要创建两个跨度——一个表示将某些内容放入缓存,另一个表示从缓存中获取某些内容。

有关可以设置的数据的详细信息,请参阅 Cache 模块开发者规范

按照以下自定义插桩说明发出缓存设置跨度:

  1. 使用你正在使用的缓存库设置缓存值。
  2. 使用 Sentry.startSpan(...) 包装你的应用程序中使用缓存值的部分。
  3. name 设置为描述性的名称,例如 "Setting auth cache"。
  4. op 设置为 cache.set
  5. cache.key 设置为表示你正在设置的键的字符串数组。
  6. 可选地,你可以设置其他属性,例如 cache.item_size。(更多信息请参阅 Cache 模块跨度数据约定。)

(上述步骤也在代码片段中进行了文档说明。)

my-cache.js
Copied
const key = "myCacheKey123";
const value = "The value I want to cache.";

Sentry.startSpan(
  {
    name: key,
    attributes: {
      "cache.key": [key],
      "cache.item_size": JSON.stringify(value).length, // Warning: if value is very big this could use lots of memory
      "network.peer.address": "cache.example.com/supercache",
      "network.peer.port": 9000,
    },
    op: "cache.put",
  },
  (span) => {
    // Set a key in your caching using your custom caching solution
    my_caching.set(key, value);
  },
);

如果你使用的缓存不支持上述自动插桩,可以使用以下自定义插桩说明来发出缓存跨度:

  1. 使用你正在使用的缓存库获取缓存值。
  2. 使用 Sentry.startSpan(...) 包装你的应用程序中从缓存中获取的部分。
  3. name 设置为描述性的名称,例如 "Getting auth cache"。
  4. op 设置为 cache.get
  5. cache.key 设置为表示你正在获取的键的字符串数组。
  6. cache.hit 设置为布尔值,表示是否成功从缓存中获取了值。
  7. 可选地,你可以设置其他属性,例如 cache.item_size。(更多信息请参阅 Cache 模块跨度数据约定。)

(上述步骤也在代码片段中进行了文档说明。)

my-cache.js
Copied
const key = "myCacheKey123";

Sentry.startSpan(
  {
    name: key,
    attributes: {
      "cache.key": [key],
      "network.peer.address": "cache.example.com/supercache",
      "network.peer.port": 9000,
    },
    op: "cache.get",
  },
  (span) => {
    // Set a key in your caching using your custom caching solution
    const value = my_caching.get(key);
    const cacheHit = Boolean(value);
    if (cacheHit) {
      span.setAttribute("cache.item_size", JSON.stringify(value).length, // Warning: if value is very big this could use lots of memory);
    }
    span.setAttribute("cache.hit", cacheHit);
  }
);

你现在应该已经正确地添加了跨度。前往 Cache 仪表板 查看你的缓存性能。