Example of calculating the size of various data in Redis

Source: Internet
Author: User
Tags foreach memory usage redis mysql database

If the MySQL database is large, we can easily find out which tables occupy the space. However, if the Redis memory is large, it is not easy to find out which tables occupy the space) the space occupied by the key.


Some tools can provide necessary help. For example, redis-rdb-tools can directly analyze RDB files to generate reports. Unfortunately, it cannot fully meet my needs, I don't want to perform secondary development on the basis of it. In fact, developing a dedicated tool is very simple. Using commands such as SCAN and DEBUG, there is not much code to achieve:

<? Php

$ Patterns = array (
'Foo:. + ',
'Bar:. + ',
'. + ',
);

$ Redis = new Redis ();
$ Redis-> setOption (Redis: OPT_SCAN, Redis: SCAN_RETRY );

$ Result = array_fill_keys ($ patterns, 0 );

While ($ keys = $ redis-> scan ($ it, $ match = '*', $ count = 1000 )){
Foreach ($ keys as $ key ){
Foreach ($ patterns as $ pattern ){
If (preg_match ("/^ {$ pattern} $/", $ key )){
If ($ v = $ redis-> debug ($ key )){
$ Result [$ pattern] + = $ v ['serializedlength'];
                }

Break;
            }
        }
    }
}

Var_dump ($ result );

?>
Of course, the premise is that you need to summarize the possible key modes in advance, the simple but not rigorous method is MONITOR:

Shell>/path/to/redis-cli monitor |
Awk-f' "'' $2 ~ "ADD | SET | STORE | PUSH" {print $4 }'
In addition, it should be noted that, because the serializedlength returned by DEBUG is the length after serialization, the final calculated value is smaller than the actual memory usage, but considering the relative size, it is still of reference significance.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.