page contents

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

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

attachments-2020-09-abyHXQdC5f508f95254ef.png

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

例如:

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


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

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 来显示了。


attachments-2020-09-B8gIpsgI5f508f820c365.jpg

  • 发表于 2020-09-03 14:39
  • 阅读 ( 650 )
  • 分类:操作系统

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
Pack
Pack

1135 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1316 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章