插桩缓存

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

Sentry 提供了一个 缓存监控仪表板,可以通过我们的 Laravel SDK 自动插桩。

如果您使用的是其他工具,可以通过以下设置说明手动插桩您的缓存操作,并使用 Sentry 查看缓存解决方案的性能。

为了让 Sentry 能够为您提供缓存性能的概览,您需要创建两个跨度(span)——一个表示将某物放入缓存,另一个表示从缓存中获取某物。

确保在创建跨度时有一个事务正在运行。更多信息请参阅 追踪

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

如果您使用的是除我们的 Laravel SDK 之外的其他工具,您需要按照以下步骤手动插桩 Cache Module

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

  1. 使用您正在使用的任何缓存库设置缓存值。
  2. 将应用程序中使用缓存值的部分包装在一个跨度内。
  3. op 设置为 cache.put
  4. cache.item_size 设置为表示缓存项大小的整数。

(上述步骤在代码片段中有详细说明。)

Copied
$key = 'cache_key';
$value = 'cache_value';

$parentSpan = \Sentry\SentrySdk::getCurrentHub()->getSpan();

if ($parentSpan !== null) {
    $context = \Sentry\Tracing\SpanContext::make()
        ->setDescription($key)
        ->setOp('cache.put');

    $span = $parentSpan->startChild($context);

    \Sentry\SentrySdk::getCurrentHub()->setSpan($span);

    // Perform you cache operation
    Cache::put($key, $value);
    
    $span
        ->setData([
            // Describe the cache server you are accessing
            'network.peer.address' => '127.0.0.1',
            'network.peer.port' => 9000,
            // Add the key you used
            'cache.key' => $key,
            // Optionally, add the size of the value you set
            'cache.item_size' => strlen($value),
        ])
        ->finish();

    \Sentry\SentrySdk::getCurrentHub()->setSpan($parentSpan);
}

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

  1. 从您正在使用的任何缓存库中获取缓存值。
  2. 将应用程序中使用缓存值的部分包装在一个跨度内。
  3. op 设置为 cache.get
  4. cache.hit 设置为一个布尔值,表示值是否成功从缓存中获取。
  5. cache.item_size 设置为表示缓存项大小的整数。

(上述步骤在代码片段中有详细说明。)

Copied
$key = 'cache_key';
$value = null;

$parentSpan = \Sentry\SentrySdk::getCurrentHub()->getSpan();

if ($parentSpan !== null) {
    $context = \Sentry\Tracing\SpanContext::make()
        ->setOp('cache.get');

    $span = $parentSpan->startChild($context);

    \Sentry\SentrySdk::getCurrentHub()->setSpan($span);

    // Perform you cache operation
    $value = Cache::get($key);
    
    $span->setData([
        // Describe the cache server you are accessing
        'network.peer.address' => '127.0.0.1',
        'network.peer.port' => 9000,
        // Add the key you just retrieved from the cache
        'cache.key' => $key
    ]);

    if ($value !== null) {
        $span->setData([
            // If you retrieved a value, the cache was hit
            'cache.hit' => true,
            // Optionally, add the size of the value you retrieved
            'cache.item_size' => strlen($value),
        ]);
    } else {
        $span->setData([
            // If you could not retrieve a value, it was a miss
            'cache.hit' => false,
        ]);
    }

    $span->finish();

    \Sentry\SentrySdk::getCurrentHub()->setSpan($parentSpan);
}

现在应该已经正确设置了相应的跨度。前往 缓存仪表板 查看您的缓存性能。