2012-07-17

Redis 导数据的 PHP 脚本

Views: 16269 | 2 Comments

Redis 本身没提供方便的导数据工具, 比如从某个 db 导数据到另一个 db, 只能自己写脚本了. redis copy.

<?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, 1000);
    $redis->select($db);
    return $redis;
}

Related posts:

  1. PHP 解码 C 字符串
  2. 用PHP遍历SSDB中的zset集合
  3. SSDB在大数据量日志分析中的应用案例
  4. 百行代码实现一个简单的Zset(SortedSet)
  5. C/C++ 语言 switch-case 后面的花括号
Posted by ideawu at 2012-07-17 12:10:52 Tags:

2 Responses to "Redis 导数据的 PHP 脚本"

Leave a Comment