www.88bifa.com:php实现redis数据库指定库号迁移的方法,使用PHP导出Redis数据到另一个Redis中的代码

正文实例陈诉了php达成redis数据库内定库号迁移的章程,分享给大家供大家参谋。具体如下:

$from = ‘127.0.0.1:6200/6’;
$to   = ‘127.0.0.1:6200/8’;

www.bifa2222.com ,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;
}
 

[root@localhost ~]# php 1.php
1/407
101/407
201/407
301/407
401/407

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

redis普通的数据库搬迁,只好整个redis
save,可能选用为主,当然也能够安装二个redis-dump,可是比较艰巨,这里提供一种php的台本,达成钦定库号的搬迁,其实也正是遍历依据存款和储蓄类型,读出来,插入新库;效果是那般:

复制代码 代码如下:

$keys  = $from_redis->keys(‘*’);
$count = 0;
$total = count($keys);
foreach($keys as $key){
www.88bifa.com:php实现redis数据库指定库号迁移的方法,使用PHP导出Redis数据到另一个Redis中的代码。    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;
    }
}

[root@localhost ~]# php 1.php
1/407
101/407
201/407
301/407
401/407