The specific use case for deleting a key after some time (expiry) in Redis using PHP is to clear up space and maintain only relevant data. This is particularly useful in scenarios such as cache management, session storage, or any temporary data storage.
expire
functionIn PHP, we can set an expiry time on a key in Redis by using the expire
function. Here's an example where we're setting an expiry of 10 seconds on a key named 'test'.
$redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis->set('test', 'value'); $redis->expire('test', 10); // key will be deleted after 10 seconds
setex
functionAlternatively, you can use the setex
method to store a key-value pair where the key automatically gets deleted after a specified amount of time.
$redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis->setex('test', 10, 'value'); // key will be deleted after 10 seconds
setex
function when you know that the key should expire at the time of setting the value itself.Yes, you can use the ttl
function in PHP to get the remaining time in seconds for a key in Redis.
$redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis->set('test', 'value'); $redis->expire('test', 10); // key will be deleted after 10 seconds echo $redis->ttl('test'); // prints the remaining time for the key in seconds
If you set a negative expiry time, the key will be deleted immediately.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.