zoukankan      html  css  js  c++  java
  • redis key全量导出与导出指定前缀的key

    redis命令列表中有两种方法可以全量导出所有的key:

    (1)keys

      由于redis是单线程的,使用keys会导致redis服务阻塞,不建议线上服务采用这种方式。

    (2)scan 命令,下面是使用scan命令实现导出全量key的代码,每次扫1000个key,结果存放到指定的文件中

      

    function redisScan($host, $port, $write_file = '/Users/admin/Documents/work/redis_test.txt') {
    
        $file_handler = fopen($write_file,'w+');
    
        $redis = new Redis();
        $redis->connect($host, $port, 5);
        $redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
    
        $it = null;
        $match = '*';
        $count = 1000;
        $tmp_result = '';
        $tmp_number = 0;
    
        do
        {
            $keysArr = $redis->scan($it,$match,$count);
            if($keysArr)
            {
                foreach ($keysArr as $key)
                {
                    $tmp_result .= $key."
    ";
                    $tmp_number++;
                }
    
                if($tmp_number >= 1000)
                {
                    fwrite($file_handler,$tmp_result);
                    $tmp_result = '';
                    $tmp_number = 0;
                }
            }
    
        }while($it > 0);
    
        if($tmp_result)
        {
            fwrite($file_handler,$tmp_result);
        }
    
        fclose($file_handler);
    
        return true;
    
    }
    

    如果需要获取指定前缀的key(以abc为例),只需要修改上述代码的match参数为 "abc*" 即可。

  • 相关阅读:
    Python 函数 -range()
    Python 函数 -xrange()
    Python 函数 -globals()
    Python 函数-max()
    Python 函数 -hasattr()
    Python 函数 memoryview()
    Python函数 hash()
    QAQ
    Õ() Big-O-notation
    一道有趣的条件概率题
  • 原文地址:https://www.cnblogs.com/smallrookie/p/9651254.html
Copyright © 2011-2022 走看看