skip to Main Content

So basically what I want to do is delete all keys from the database if its size is less than 1GB. I want to do it from a PHP script with follwoing code.

<?php 

   //Connecting to Redis server
   $redis = new Redis(); 

   $redis->connect('127.0.0.1', 6379); 

   echo "Connection to server sucessfully"; 

   $redis->select(0);
   $memstats = $redis->info("memory");
   
   if ($memstats["used_memory"] < 8589934592){
   
   $redis->flushAll();
   
   }else{
   
   echo "Mem is less than 1GB";
   
   }

?>

I am using phpredis for this and just not sure about few things.

  • Does this used_memory parameters represents current database size?
  • Am I doing it right?
  • If not then how to get current database size?

Thank you. I do not have much idea of working with Redis.

2

Answers


  1. Refer this link to understand the memory stats

    The "total_system_memory_human" shows the total amount of memory that the Redis host has. And "used_memory_human" shows the total amount of used memory, which includes data and overhead.

    Moreover, I would recommend to set expiry on the keys instead of deleting data based on such conditions.

    Login or Signup to reply.
    • Does this used_memory parameters represents current database size?

      To my knowledge, there is no way to know the size of a single database in bytes. However, you can see the size of all databases in bytes using the info command as you did. However, if you only care about the databases’ general size, then the required parameter is used_memory_dataset. The used_memory parameter is for the size of the whole Redis program/instance. Read the INFO page for more details.

    • Am I doing it right?

      You are doing almost right. 8589934592 is 8 GB, not 1 GB. You should define a constant then use it like this:

      define( 'ONE_GIGABYTE', 1073741824 );
      
      if ($memstats["used_memory"] < ONE_GIGABYTE){
        $redis->flushAll();
      } else {
        echo "Mem is NOT less than 1GB";
      }
      
    • If not then how to get current database size?

      Again, to my knowledge, there is no way to know the size of a single database in bytes. You can see the number of keys in the currently-selected database using the command DBSIZE like this: $count = $redis->dbSize();

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search