Home > Backend Development > PHP Tutorial > Example sharing of php migrating redis specified library number

Example sharing of php migrating redis specified library number

*文
Release: 2023-03-18 11:24:01
Original
1284 people have browsed it

有些时候需求变动会涉及到迁移数据库,那么redis数据库指定库号迁移需要如何操作呢?本文通过介绍了php实现redis数据库指定库号迁移的方法,希望使大家对redis数据库指定库号迁移有一定的了解。

redis普通的数据库迁移,只能整个redis save,或者利用主从,当然也可以安装一个redis-dump,不过比较麻烦,这里提供一种php的脚本,实现指定库号的迁移,其实也就是遍历根据存储类型,读出来,插入新库,效果是这样:

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

PHP实例代码如下:

<?php 
$from = &#39;10.0.2.52:6379/7&#39;; 
$to   = &#39;127.0.0.1:6379/7&#39;; 
$from_redis = redis_init($from); 
$to_redis   = redis_init($to); 
$keys  = $from_redis->keys(&#39;*&#39;); 
$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(&#39;/^([^:]+)(:[0-9]+)?\\/(.+)?/&#39;, $conf, $ms); 
    $host = $ms[1]; 
    $port = trim($ms[2], &#39;:&#39;); 
    $db = $ms[3]; 
    $redis->connect($host, $port); 
    $redis->select($db); 
    return $redis; 
} 
?>
Copy after login

相关推荐:

关于Redis集群故障的分析

详解Redis的主从同步

redis计数器防止刷单方法介绍

The above is the detailed content of Example sharing of php migrating redis specified library number. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template