redis里通过命名空间存储缓存,根据结构生成树型

336 阅读1分钟

一般为了方便管理 redis 缓存,我们通过 : 来分隔不同的 key 来进行存储缓存,这样方便查看。

例如:

game:upload_role:1000
game:member_info:2000
game:member_info:state_info:3000

上面的这种结构在 Redis Desktop Manager 中就会显示如下:

![](https://pic4.zhimg.com/80/v2-f1a9fdaaefafce8ff2cf116cfdd74269_720w.jpg)

我们可以通过 keys 命令来获取 redis 里的所有 key。但这些 key 是没有层次的,如何生成?

只能通过 : 分隔符来处理各 key 的上下层关系。

代码如下:

function relationCache($keys, &$index, &$index_tree)
{
    $result = [];
    if ($keys) {
        foreach ($keys as $key) {
            $arr = explode(':', $key);
            $len = count($arr);

            for ($ix = 0; $ix < $len; $ix++) {
                $cur_key = implode(':', array_slice($arr, 0, $ix + 1));

                if (!isset($index_tree[$cur_key])) {
                    $index_tree[$cur_key] = $index++;

                    $pid = 0;
                    if ($ix >= 1) {
                        $pre_key = implode(':', array_slice($arr, 0, $ix));
                        $pid = $index_tree[$pre_key];
                    }

                    $result[] = [
                        'id' => $index_tree[$cur_key],
                        'pid' => $pid,
                        'name' => $arr[$ix],
                        'key' => $cur_key,
                    ];
                }
            }
        }
    }
    return $result;
}

然后生成树型的函数如下:

function genTree($items, $id = 'id', $pid = 'pid', $son = 'child')
{
    $tree = array();
    $tmpMap = array();

    foreach ($items as $item) {
        $tmpMap[$item[$id]] = $item;
    }

    foreach ($items as $item) {
        if (isset($tmpMap[$item[$pid]])) {
            $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
        } else {
            $tree[] = &$tmpMap[$item[$id]];
        }
    }
    unset($tmpMap);
    return $tree;
}

使用如下:

$keys = [
    'game:upload_role:1000',
    'game:member_info:2000',
    'game:member_info:state_info:3000',
];

//索引
$index = 1;
//索引树
$index_tree = [];

//注意,如果想多次调用relationCache,并共享索引,请通过外部传参的方式
$result = relationCache($keys, $index, $index_tree);

$result = genTree($result, 'id', 'pid', 'children');

echo '<pre>';
print_r($result);

这样生成的结果,通过json_encode就可以使用 zTree 来显示了。

以上内容希望帮助到大家,很多PHPer在进阶的时候总会遇到一些问题和瓶颈,业务代码写多了没有方向感,不知道该从那里入手去提升,对此我整理了一些资料,包括但不限于:分布式架构、高可扩展、高性能、高并发、服务器性能调优、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql优化、shell脚本、Docker、微服务、Nginx等多个知识点高级进阶干货需要的可以免费分享给大家,需要戳这里 PHP进阶架构师>>>实战视频、大厂面试文档免费获取