Introduction:
In web development, persistent data storage is crucial. Redis, as a high-performance key-value store, is well-suited for caching and storing data. This article explains how to use PHP together with Redis to achieve persistent data storage.
a) Open the configuration file:
<span class="fun">vim /etc/redis/redis.conf</span>
b) Set a Redis password:
<span class="fun">requirepass your_password</span>
c) Save and close the file.
<span class="fun">redis-server</span>
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('your_password'); // Authenticate if password set
$redis->set('my_key', 'my_value');
$value = $redis->get('my_key');
echo $value; // Outputs my_value
Serialize arrays or objects before storing:
$data = ['name' => 'John', 'age' => 25];
$redis->set('my_data', serialize($data));
Deserialize when retrieving:
$data = unserialize($redis->get('my_data'));
print_r($data); // Outputs array content
By default, Redis stores data in memory and will lose data on restart. To ensure data safety, Redis offers two persistence methods: RDB and AOF.
Redis creates snapshot files saving memory data to disk at intervals.
save 900 1
save 300 10
save 60 10000
These configurations define the intervals and data change thresholds for snapshots.
After restart, Redis restores data from the latest snapshot but may lose data changed after the snapshot.
AOF persistence records every write command; on restart, Redis replays commands to restore data.
appendonly yes
appendfilename "appendonly.aof"
This article has explained how to connect PHP with Redis and use Redis’s RDB and AOF mechanisms for data persistence. Proper configuration ensures data survives Redis server restarts, improving data reliability and application stability.