> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 监控数据库事务的执行时间

> 介绍如何使用 Laravel 13 的 Connection::whenTransactionRunsLongerThan，在提交或回滚时检测长时间运行的事务。

排查事务延迟时，除了 SQL 的执行时间，还需要关注事务内执行的应用程序代码以及数据库锁等待时间。Laravel 13.x 的 `Connection::whenTransactionRunsLongerThan` 会在事务的整体耗时超过指定阈值时调用 callback。

> [!NOTE]
>
> 本页基于 [Laravel Framework 13.x 的实现](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Connection.php)。请确认你使用的 Framework 版本包含此方法。

## 注册 callback

要监控整个应用程序的数据库连接，请在 service provider 的 `boot` 方法中注册。阈值的单位是 **毫秒**。

```php theme={null}
<?php

namespace App\Providers;

use Illuminate\Database\Connection;
use Illuminate\Database\Events\TransactionCommitted;
use Illuminate\Database\Events\TransactionRolledBack;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        DB::connection()->whenTransactionRunsLongerThan(
            500,
            function (
                Connection $connection,
                TransactionCommitted|TransactionRolledBack $event,
                float $duration,
            ): void {
                Log::warning('Long database transaction detected.', [
                    'connection' => $connection->getName(),
                    'duration_ms' => $duration,
                    'event' => $event::class,
                ]);
            },
        );
    }
}
```

callback 会接收以下 3 个参数。

* `Connection`: 被监控的数据库连接
* `TransactionCommitted|TransactionRolledBack`: 表示事务是 commit 还是 rollback 的 event
* `float`: 测得的耗时（毫秒）

像 `DB::connection('mysql')` 这样指定连接名，就可以只监控特定连接。要监控多个连接，请分别在每个 `Connection` 上注册 callback。

## 测量范围

测量在外层事务开始时开始，在外层事务 commit 或 rollback 时结束。

```php theme={null}
DB::transaction(function () {
    // 从这里开始测量

    Order::create($orderData);

    DB::transaction(function () {
        // 内层 transaction 不会单独测量
        Inventory::reserve($product);
    });

    // 在这里结束测量，如果超过阈值就会调用 callback
});
```

Laravel 仅在 transaction level 从 `0` 变为 `1` 时保存开始时间。因此，即使内层 transaction 以 savepoint 方式运行，内层的处理时间也会计入外层事务的耗时。它并不是用于以单独阈值监控内层 transaction 的机制。

callback 会在 transaction level 回到 `0` 之后调用。即使 `DB::transaction` 的 callback 抛出异常并 rollback，也能收到 `TransactionRolledBack` event 和测得的时间。手动调用 `beginTransaction` / `commit` / `rollBack` 时也会触发相同的 event。

## 阈值的指定方式

`whenTransactionRunsLongerThan` 的第 1 个参数可以传入以下形式。

| 值 | 含义 |
| - | - |
| `int` 或 `float` | 毫秒 |
| `CarbonInterval` | interval 的总毫秒数 |
| `DateTimeInterface` | 到指定时间为止的秒数换算成毫秒后的值 |

通常直接指定毫秒就足够了。如果希望以时间单位表达，可以使用 `CarbonInterval`。

```php theme={null}
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\DB;

DB::connection()->whenTransactionRunsLongerThan(
    CarbonInterval::seconds(1),
    static function (): void {
        // 记录用于监控的日志或 metrics
    },
);
```

判断依据是“耗时是否大于阈值”。耗时与阈值相等时不会调用 callback。将阈值设为 `0` 时，所有被测量的 transaction 都会触发 callback。

## 与 SQL 延迟区分开来

Laravel 还提供 `whenQueryingForLongerThan`，用于监控单个 request 内执行的 SQL 的累计时间。两个 API 的测量对象不同。

| API | 测量对象 | callback 的 event |
| - | - | - |
| `whenQueryingForLongerThan` | request 内 SQL 执行时间的累计 | `QueryExecuted` |
| `whenTransactionRunsLongerThan` | 从外层 transaction 开始到 commit 或 rollback 的耗时 | `TransactionCommitted` 或 `TransactionRolledBack` |

如果在事务内调用外部 API 或发生锁等待，事务的耗时可能会大于 SQL 的累计时间。同时记录两者，更容易区分延迟是来自 SQL 本身，还是来自事务内的其他处理。

## 运维注意事项

callback 在 commit 或 rollback 的处理过程中调用，因此应仅用于监控。可以输出日志或记录 metrics，但不要在同一连接上执行额外的更新，也不要进行耗时的外部通信。

此外，在事务内调用外部 API 时，其等待时间也会被计入。考虑能否把外部通信移到事务之外，这不仅能减少通知，还能缩短锁的持有时间。

## 参考的一手资料

* [Laravel 官方数据库文档](https://github.com/laravel/docs/blob/13.x/database.md)
* [`Connection::whenTransactionRunsLongerThan` 的实现](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Connection.php)
* [添加到 Laravel Framework 的提交](https://github.com/laravel/framework/commit/5edfeeed86961983042d0bdbbe7265d5b6dc7bba)


## Related topics

- [进阶主题](https://kawax.biz/zh-CN/advanced/index.md)
- [数据库配置](https://kawax.biz/zh-CN/database.md)
- [数据库测试](https://kawax.biz/zh-CN/database-testing.md)
- [Eloquent Observer 与模型事件](https://kawax.biz/zh-CN/advanced/eloquent-observers.md)
- [队列任务的执行控制](https://kawax.biz/zh-CN/advanced/queue-job-control.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.