Şivā SankĂr
Şivā SankĂr

Reputation: 2036

Dump and Restore Redis on PHP (predis)

How can I dump and restore the redis database on PHP, I'm using predis on my client.

Can I dump the redis database on .rdb format ?

Updated :

I dump/backup database using the following command,

$redis->bgSave();

How to restore it back to my database ?

Upvotes: 1

Views: 2511

Answers (2)

Şivā SankĂr
Şivā SankĂr

Reputation: 2036

As Malinga, Restoring happen in the restart of redis server. So you need set appendonly no. So that it will use the .rdb file.

So, I created a sample program to backup and restore redis database, Here is the code you can check

Export :

$i = 0;
$json = array();
foreach($redis->keys('*') as $key) {
    $data = array();
    $data['key'] = $key;
    $data['ttl'] = $redis->ttl($key);
    $data['value'] = bin2hex($redis->dump($key));
    $json[$i] = $data;
    $i++;
}
header('Content-disposition: attachment; filename=database.json');
header('Content-type: application/json');
echo json_encode($json);

Import :

if (isset($_POST['submit']) && $_POST['submit'] == 'Import') {
    $types = array(
        'application/json',
        'application/octet-stream'
    );
    if (in_array($_FILES['upload']['type'], $types)) {
        var_dump($_FILES);
        if (move_uploaded_file($_FILES['upload']['tmp_name'], 'uploads/' . $_FILES['upload']['name']))
            {
            $file = file_get_contents('uploads/' . $_FILES['upload']['name'], "r");
            $database = json_decode($file, true);
            foreach($database as $data)
                {
                if ($data['ttl'] >= 0)
                    {
                    $data['ttl'] = $data['ttl'];
                    }
                  else
                    {
                    $data['ttl'] = 0;
                    }

                if ($data['key'] && $data['value'] && !$redis->exists($data['key']))
                    {
                    $redis->restore($data['key'], $data['ttl'], hex2bin($data['value']));
                    }
                }
            }
        }
}

Full code can be downloaded via GitHub

Upvotes: 3

Malinga
Malinga

Reputation: 515

In redis you can use SAVE or BGSAVE to create a snapshot. However use of BGSAVE is recommended as SAVE will block all the other clients.

To do that in predis, it should be possible through

$client->executeRaw(['BGSAVE']);

Sorry I haven try this with predis. So first check if the client allow something like

$client->bgsave(); 

if not try above

Restoring happen in the restart of redis server. So you need set appendonly no. So that it will use the .rdb file

Upvotes: 1

Related Questions