请问下现阶段是否有必要使用异步mysql查询?

Jinson

问题描述

由于pdo查询是阻塞的,我想着把pdo查询改成异步查询减少接口请求时间,然后在本地用单进程分别试了下 pdoamphp/mysql,多次查询时,异步查询确实将接口请求时间显著减少,但是上wrk压测多次查询数据库时,amp 却卡死了~

控制器代码:

<?php

namespace app\admin\controller\system;

use app\bootstrap\AmpMysqlDb;
use support\basic\controller\BaseController;
use support\basic\db\AsyncQuery;
use support\Db;
use support\Request;
use function Amp\async;
use function Amp\Future\await;

class IndexController extends BaseController
{
    // pdo单次查询
    public function simplePDO()
    {
        return Db::table('system_users')->find(random_int(1, 499500));
    }
    // amp单次查询
    public function simpleAsync()
    {
        $pool      = AmpMysqlDb::getPool();
        $statement = $pool->prepare('SELECT * FROM wa_system_users WHERE id = :id');
        return $statement->execute(['id' => random_int(1, 499500)])->fetchRow();
    }

    //pdo查询
    public function multiPDO(int $frequency = 10): array
    {
        $users = [];
        for ($i = 0; $i < $frequency; $i++) {
            $users[] = Db::table('system_users')->find(random_int(1, 499500));
        }
        return $users;
    }

    //异步查询
    public function multiAsync(): array
    {
        $futures = [];
        for ($i = 0; $i < 10; $i++) {
            $futures[] = async(function () {
                $sql = 'SELECT * FROM wa_system_users WHERE id = :id';
                return AsyncQuery::raw($sql, ['id' => random_int(1, 499500)]);
            });
        }
        $data   = await($futures);
        $result = [];
        foreach ($data as $datum) {
            $result[] = $datum->fetchRow();
        }
        return $result;
    }

    public function index()
    {
        $result = $this->multiPDO();
        return $this->success('成功', $result);
    }
}

连接池代码:

<?php
declare(strict_types=1);

namespace app\bootstrap;

use Amp\Mysql\MysqlConfig;
use Amp\Mysql\MysqlConnectionPool;
use Webman\Bootstrap;
use Workerman\Worker;

class AmpMysqlDb implements Bootstrap
{
    /** @var MysqlConnectionPool[] */
    private static array $pool = [];
    private static string $default = '';

    private const ALLOW_OPTIONS = [
        'host',
        'port',
        'user',
        'password',
        'db',
        'charset',
        'collate',
        'compression',
        'local-infile',

        'username',
        'database'
    ];

    public static function start(?Worker $worker): void
    {
        $config      = config('database', []);
        $connections = $config['connections'] ?? [];
        if (!$connections) {
            return;
        }

        $default = $config['default'] ?? false;
        foreach ($connections as $name => $config) {
            if ($config['driver'] == 'mysql') {
                if ($name == $default) {
                    self::$default = $name;
                }
                $dsn               = self::getDsn($config);
                $mysqlConfig       = MysqlConfig::fromString(trim($dsn));
                self::$pool[$name] = new MysqlConnectionPool($mysqlConfig, $config['pool_size'] ?? 10);
            }
        }
    }

    public static function getPool(string $connection = ''): MysqlConnectionPool
    {
        if (empty($connection)) {
            if (empty(self::$default)) {
                throw new \RuntimeException('Default database connection not configured.');
            }
            $connection = self::$default;
        }

        if (!isset(self::$pool[$connection])) {
            throw new \InvalidArgumentException("Database connection '{$connection}' not found.");
        }
        return self::$pool[$connection];
    }

    /**
     * @param array $config
     * @return string
     */
    protected static function getDsn(array $config): string
    {
        $dsn = '';
        foreach ($config as $key => $value) {
            if (in_array($key, static::ALLOW_OPTIONS, true)) {
                if (!$value) {
                    continue;
                }

                $key = match ($key) {
                    'username' => 'user',
                    'database' => 'db',
                    default => $key
                };
                $dsn .= "{$key}={$value} ";
            }
        }

        return $dsn;
    }

}

上wrk压测接口,

环境:

Workerman[start.php] status
Start worker in DEBUG mode.
---------------------------------------------------GLOBAL STATUS---------------------------------------------------------
Workerman/5.0.0-rc.3    PHP/8.2.23 (Jit on)           Linux/5.4.0-200-generic
start time:2024-12-03 17:04:11   run 0 days 0 hours   load average: 0.34, 0.25, 0.28
3 workers    3 processes
name                          event-loop     exit_status     exit_count
webman                        revolt         0               0               
monitor                       revolt         0               0               
plugin.webman.push.server     revolt         0               0               
---------------------------------------------------PROCESS STATUS--------------------------------------------------------
pid memory  listening                name                      connections send_fail timers  total_request qps    status
19314   2.52M   http://0.0.0.0:8787      webman                    0           0         1       0             0      [idle]
19315   2.6M    none                     monitor                   0           0         2       0             0      [idle]
19316   2.58M   websocket://0.0.0.0:3131 plugin.webman.push.server 0           0         3       0             0      [idle]
---------------------------------------------------PROCESS STATUS--------------------------------------------------------
Summary 7.7M    -                        -                         0           0         6       0             0      [Summary]

数据库:随机生成50w条记录的用户表

  1. 单进程,接口单次查询数据库的情况下,amp(454.52 qps)只有 pdo(2824.80 qps)的七分之一左右

    pdo结果:

    [root@dev backend-webman]# wrk -c200 -t5 -d3s http://127.0.0.1:8787/admin/system/index
    Running 3s test @ http://127.0.0.1:8787/admin/system/index
     5 threads and 200 connections
     Thread Stats   Avg      Stdev     Max   +/- Stdev
       Latency    94.22ms  238.98ms   1.98s    92.91%
       Req/Sec     0.91k   368.56     1.84k    69.07%
     8757 requests in 3.10s, 5.73MB read
     Socket errors: connect 0, read 0, write 0, timeout 25
    Requests/sec:   2824.80
    Transfer/sec:      1.85MB

    amp结果:

    [root@dev backend-webman]# wrk -c200 -t5 -d3s http://127.0.0.1:8787/admin/system/index
    Running 3s test @ http://127.0.0.1:8787/admin/system/index
     5 threads and 200 connections
     Thread Stats   Avg      Stdev     Max   +/- Stdev
       Latency   408.22ms   80.73ms 527.62ms   87.97%
       Req/Sec   109.36     74.59   326.00     65.42%
     1372 requests in 3.02s, 0.90MB read
    Requests/sec:    454.52
    Transfer/sec:    304.74KB
  2. 单进程,接口查询10次数据库的情况下,amp(卡死),pdo(344qps)
    pdo结果:

    [root@dev backend-webman]# wrk -c200 -t5 -d3s http://127.0.0.1:8787/admin/system/index
    Running 3s test @ http://127.0.0.1:8787/admin/system/index
     5 threads and 200 connections
     Thread Stats   Avg      Stdev     Max   +/- Stdev
       Latency   119.01ms  179.82ms   1.99s    97.11%
       Req/Sec   159.37     62.02   290.00     76.27%
     938 requests in 3.01s, 4.65MB read
     Socket errors: connect 0, read 0, write 0, timeout 8
    Requests/sec:    311.36
    Transfer/sec:      1.55MB

    amp结果:

    root@dev backend-webman]# wrk -c200 -t5 -d3s http://127.0.0.1:8787/admin/system/index
    Running 3s test @ http://127.0.0.1:8787/admin/system/index
     5 threads and 200 connections
     Thread Stats   Avg      Stdev     Max   +/- Stdev
       Latency   815.46ms  612.26ms   1.78s    58.33%
       Req/Sec     4.47      4.85    20.00     82.35%
     18 requests in 3.02s, 91.47KB read
     Socket errors: connect 0, read 0, write 0, timeout 6
    Requests/sec:      5.95
    Transfer/sec:     30.25KB
    [root@dev backend-webman]# curl http://127.0.0.1:8787/admin/system/index
    ^C
    [root@dev backend-webman]#

​ 卡死了,是连接池耗尽,将mysql最大连接数改成1000,然后又把连接池数量改成900

new MysqlConnectionPool($mysqlConfig, 900);

再次测试amp结果:

[root@dev backend-webman]# wrk -c200 -t5 -d3s http://127.0.0.1:8787/admin/system/index
Running 3s test @ http://127.0.0.1:8787/admin/system/index
  5 threads and 200 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   572.83ms  400.34ms   1.98s    74.15%
    Req/Sec    44.92     23.62   140.00     67.86%
  381 requests in 3.01s, 1.89MB read
  Socket errors: connect 0, read 0, write 0, timeout 29
Requests/sec:    126.42
Transfer/sec:    642.39KB

测试结果不及预期,这结果感觉没必要上异步查询了,毕竟这还只是单进程下开1000个连接池,多开进程的时候数据库连接数太多反而导致性能降低。

不知道是不是我姿势不对,有没有大佬指点一下?

401 2 0
2个回答

walkor 打赏

目前看不管是 amphp/mysql,还是swoole swow协程,cpu跑满的情况下,它们的极限性能都没有多进程pdo阻塞性能高。

amphp/mysql应该是php解析的mysql协议,PHP做协议解析会比c语言消耗很多cpu。所以cpu跑满的情况下,amphp/mysql比阻塞pdo性能差更多。
如果是服务器负载不高的情况下,通过连接池并发查询可以减少多个SQL的总体等待时间,表象就是响应速度会很快。但是实际上这个快可以看作是以消耗更多cpu的代价换来的。当请求量变大,则性能会急剧下降。

如果业务请求量不大,想要提高响应速度,可以尝试 amphp/mysql。但是相比 amphp/mysql ,使用swoole或者swow驱动科效果会更好,前提是你了解使用协程带来的副作用,例如全局变量污染,上下文传递,还有考虑compsoer其他组件兼容问题。

  • Jinson 15天前

    感谢解答,如果要使用swoole或者swow就上hyperf了,就是比较喜欢webman,所以尝试下workerman 5.0用revolt/event-loop。业务请求量不大,想要提高响应速度,可以考虑用在后台管理上,不过既然是后台使用,速度稍微慢点倒也能接受

  • wudx8 7天前

    其实可以写一些工具方法。 在特定的场景里,检测到安装swoole扩展就使用协程。 用起来很方便的。

evilk

我认为,正确的方向,应该是,通过 优化SQL 来减少查询时间

  • Jinson 14天前

    是,有时候做统计,需要查询几个表比较慢,这个实验一下能否异步查询减少耗时。不过现在统计基本都丢clickhouse里搞,那个支持异步

  • ngrok.cc内网穿透 5天前

    做统计,你可以不用全表统计,采用增量统计,就是每次统计不是统计所有的,而是累加的。这样可以减少数据库的消耗

×
🔝