Home  >  Article  >  Backend Development  >  Statistical examples of the size of various data in Redis

Statistical examples of the size of various data in Redis

小云云
小云云Original
2017-12-13 14:22:111642browse

本文我们和大家分享Redis中各种数据的大小的统计示例,如何统计Redis中各种数据的大小呢,下面我们就一起来看看这个关于统计Redis中各种数据的大小的例子,具体操作如下所示。

如果 MySQL 数据库比较大的话,我们很容易就能查出是哪些表占用的空间;不过如果 Redis 内存比较大的话,我们就不太容易查出是哪些(种)键占用的空间了。


 有一些工具能够提供必要的帮助,比如 redis-rdb-tools 可以直接分析 RDB 文件来生成报告,可惜它不能百分百实现我的需求,而我也不想在它的基础上二次开发。实际上开发一个专用工具非常简单,利用 SCAN 和 DEBUG 等命令,没多少行代码就能实现:

<?php
$patterns = array(      &#39;foo:. &#39;,      &#39;bar:. &#39;,      &#39;. &#39;,  );
$redis = new Redis(); 
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
$result = array_fill_keys($patterns, 0);
while ($keys = $redis->scan($it, $match = &#39;*&#39;, $count = 1000))
 {      foreach ($keys as $key)
  {          foreach ($patterns as $pattern) 
 {              if (preg_match("/^{$pattern}$/", $key)) 
 {                  if ($v = $redis->debug($key)) 
 {                      $result[$pattern]  = $v[&#39;serializedlength&#39;];  
                 }
                break;      
                        }      
                            }   
                               } 
                                }
var_dump($result);
?>
 当然,前提是你需要提前总结出可能的键模式,简单但不严谨的方法是 MONITOR:
shell> /path/to/redis-cli monitor |         awk -F &#39;"&#39; &#39;$2 ~ "ADD|SET|STORE|PUSH" {print $4}&#39;

 此外,需要注意的是:因为 DEBUG 返回的 serializedlength 是序列化后的长度,所以最终计算的值小于实际内存占用,但考虑到相对大小依然是有参考意义的。

相关推荐:

php中Redis函数的用法总结

Redis集群搭建全记录

Redis中整数小集合

The above is the detailed content of Statistical examples of the size of various data in Redis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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