陈大剩博客

利用原生swoole协程批量向数据库插入1000W条数据

  • 陈大剩
  • 2020-09-24 20:47:20
  • 4679

一直再听说高并发,没有体验过真正的高并发,这次体验下1000w数据表(不知道算不算大数据),刚好体验下mysql索引的性能;
这次带大家体验下上千万的表并发查询操作,本例用的是swoole协程,插入1000W条数据(引用官方demo);
固态硬盘大概30分钟左右,机械硬盘可自行测试,可修改for循环中的个数控制插入条数;

<?php
/**
 * @author ChenDasheng
 * @created 2020/9/13 1:47
 */
declare(strict_types=1);

use Swoole\Coroutine;
use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;
use Swoole\Runtime;

// 线程数
const N = 1024;

Runtime::enableCoroutine();
// 记录时间
$s = microtime(true);
// 开启容器
Coroutine\run(function () {
//mysql 连接池 因为是教程 就没有去检测在连接中特殊情况
    $pool = new PDOPool((new PDOConfig)
        ->withHost('127.0.0.1')
        ->withPort(3306)
        ->withDbName('demo')
        ->withCharset('utf8mb4')
        ->withUsername('root')
        ->withPassword('123456')
    );
//循环写入数据库
    for ($n = 1024; $n--;) {
        Coroutine::create(function () use ($pool) {
            $pdo = $pool->get();
            for ($i = 10000; $i--;) {
                $statement = $pdo->prepare('INSERT INTO customers1 (`name`,`city`,`gender`,`birthdate`,`mobile`,`photo`,`monthsalary`,`yearbonus`) value (?,?,?,?,?,?,?,?)');
                if (!$statement) {
                    throw new RuntimeException('Prepare failed');
                }
                $a = mt_rand(1, 10);
                $b = mt_rand(1, 100);
                $result = $statement->execute([getChar(mt_rand(2, 4)), getChar(mt_rand(2, 4)), $a, date('Y-m-d', mt_rand(strtotime('2020-01-01'), strtotime('2021-01-01'))),   '155'.mt_rand(10000000,99999999), $a, $a, $b]);
                if (!$result) {
                    throw new RuntimeException('Execute failed');
                }
            }
            $pool->put($pdo);
        });
    }
});


$s = microtime(true) - $s;
echo 'Use ' . $s . 's for ' . N . ' queries' . PHP_EOL;

/**
 * 自动生成汉字
 * @param $num 为生成汉字的数量
 * @return string
 * @author ChenDasheng
 * @created 2020/9/24 20:36
 */
function getChar($num)
{
    $b = '';
    for ($i = 0; $i < $num; $i++) {
        // 使用chr()函数拼接双字节汉字,前一个chr()为高位字节,后一个为低位字节
        $a = chr(mt_rand(0xB0, 0xD0)) . chr(mt_rand(0xA1, 0xF0));
        // 转码
        $b .= iconv('GB2312', 'UTF-8', $a);
    }
    return $b;
}
分享到:
4

说点儿什么吧

头像

表情

本站由陈大剩博客程序搭建 | 湘ICP备2023000975号| Copyright © 2017 - 陈大剩博客 | 本站采用创作共用版权:CC BY-NC 4.0

站长统计| 文章总数[109]| 评论总数[9]| 登录用户[22]| 时间点[112]

logo

登入

社交账号登录