Merge Two Redis Databases via PHP

Posted on October 19, 2018 at 3:23 pm

Simple PHP script I used to merge two Redis databases. In short, the PHP script adds all redis-1 database (0) data to redis-2 database (0). The PHP script first retrieves all keys->values from redis-1 database (0) and then it adds via set() all keys->values to redis-2 database (0).

// Connect to Redis Database 1
 
$redis1 = new Redis(); 
 
try 
{
    $connected = $redis1->connect('127.0.0.1', 6379, 1);
}
catch(Exception $e) 
{
    echo "Failed to connect to Redis database 1: ".$e->getMessage();
 
	return;
}
 
if(!$connected)
{
    echo "Failed to connect to Redis database";
 
	return;
}
 
$redis1->auth('password');
 
$redis1->select(0);
 
// Connect to Redis Database 2
 
$redis2 = new Redis(); 
 
try 
{
    $connected = $redis2->connect('127.0.0.2', 6379, 1);
}
catch(Exception $e) 
{
    echo "Failed to connect to Redis database 2: ".$e->getMessage();
 
	return;
}
 
if(!$connected)
{
    echo "Failed to connect to Redis database";
 
	return;
}
 
$redis2->auth('password');
 
$redis2->select(0);
 
// Add all keys and values from Redis 1 to Redis 2
 
$keys = $redis1->keys('*');
 
foreach($keys as $key)
{
	echo "Key: ".htmlspecialchars($key)." -> Value: ".htmlspecialchars($redis1->get($key))."<br />";
 
	$redis2->set($key, $redis1->get($key));
}
 
echo "Done";

Receive updates via email

Other Posts

Updated Posts