码迷,mamicode.com
首页 > 其他好文 > 详细

redis管道pipeline的运用

时间:2018-07-05 21:30:01      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:server   管道   hello   pes   txt   serve   hash   try   null   

写入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();
}

redis管道pipeline的运用

标签:server   管道   hello   pes   txt   serve   hash   try   null   

原文地址:http://blog.51cto.com/phpme/2136827

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!