直接上代碼吧
配置文件中開啟鍵空間通知 notify-keyspace-events Ex
1.新建index.php
$redis = new \Redis();
//連接本地的 Redis 服務
$redis->connect("127.0.0.1", 6379);
$redis->setOption(\Redis::OPT_READ_TIMEOUT,-1);
echo "訂閱消息監聽 \n";
$redis->psubscribe(array('__keyevent@0__:expired'), 'psCallback');
function psCallback($redis, $pattern, $chan, $msg)
{
echo "Pattern: $pattern\n";
echo "Channel: $chan\n";
echo "Msg: $msg\n";
}
執行php index.php
2.新建文件index2.php
$redis = new \Redis();
//連接本地的 Redis 服務
$redis->connect("127.0.0.1", 6379);
$redis->set("name", "test");
$redis->expire("name", 3);
3.3秒后輸出