欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用PHP导出Redis数据到另一个Redis中的代码

程序员文章站 2023-11-22 15:44:58
从某个 redis db 导出数据到另一个 redis db 的php脚本:复制代码 代码如下:$from = '127.0.0.1:6200/6';$to &n...

从某个 redis db 导出数据到另一个 redis db 的php脚本:

复制代码 代码如下:
$from = '127.0.0.1:6200/6';
$to   = '127.0.0.1:6200/8';

$from_redis = redis_init($from);
$to_redis   = redis_init($to);

$keys  = $from_redis->keys('*');
$count = 0;
$total = count($keys);
foreach($keys as $key){
    if(++$count % 100 == 1){
        echo "$count/$total\n";
    }
    $type = $from_redis->type($key);
    switch($type){
        case redis::redis_string:
            $val = $from_redis->get($key);
            $to_redis->set($key, $val);
            break;
        case redis::redis_list:
            $list = $from_redis->lrange($key, 0, -1);
            foreach($list as $val){
                $to_redis->rpush($key, $val);
            }
            break;
        case redis::redis_hash:
            $hash = $from_redis->hgetall($key);
            $to_redis->hmset($key, $hash);
            break;
        case redis::redis_zset:
            $zset = $from_redis->zrange($key, 0, -1, true);
            foreach($zset as $val=>$score){
                $to_redis->zadd($key, $score, $val);
            }
            break;
    }
}

function redis_init($conf){
    $redis = new redis();
    preg_match('/^([^:]+)(:[0-9]+)?\\/(.+)?/', $conf, $ms);
    $host = $ms[1];
    $port = trim($ms[2], ':');
    $db = $ms[3];
    $redis->connect($host, $port);
    $redis->select($db);
    return $redis;
}