redis管道pipeline的运用

写入100万条数据到指定文件

declare(strict_types=1);//开启强类型模式

function random($length, $numeric = false)
{
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    if ($numeric) {
        $hash = '';
    } else {
        $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
        $length--;
    }
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    return $hash;
}

$filePath = './data.txt';
for ($i = 0; $i <= 1000000; $i++) {
    $str = random(10, true);
    file_put_contents($filePath, $str . PHP_EOL, FILE_APPEND);
}

读取文件并写道redis

$lines = file_get_contents($filePath);//获取文件内容
ini_set('memory_limit', '-1');//不要限制Mem大小,否则会报错

$arr = explode(PHP_EOL, $lines);//转换成数组

//echo $arr['1000000'] ?? 'null';

try {
    $redis = new \Redis();
    $redis->connect('192.168.1.9', 6379);
    $redis->auth('*****');//密码验证
    $redis->select(0);//选择库
    $redis->pipeline();//开启管道

    foreach ($arr as $key => $value) {
        $redis->hsetNx('helloworld', (string)$key, $value);
    }
    $redis->exec();

    echo $redis->hGet('helloworld', '1000000') . PHP_EOL;
    echo $redis->hGet('helloworld', '1000001') . PHP_EOL;
} catch (\Exception $e) {
    echo $e->getMessage();
}

猜你喜欢

转载自blog.51cto.com/phpme/2136827