1.修改redis配置文件
notify-keyspace-events "Ex"
2.修改datebase配置文件
'notify_cache' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 4),
'read_write_timeout' => -1, // 读写超时设定
],
3.创建过期key
$ttl = strtotime($data['return_time']) - time() - 600;
$redis = Redis::connection('notify_cache');
$redis->set('NOTIFY_CONFIRM:'.$id,$id);
$redis->expire('NOTIFY_CONFIRM:'.$id,$ttl);
4.创建监听队列
$cache_db = config('database.redis.notify_cache.database',4);
$pattern = '__keyevent@'.$cache_db.'__:expired';
Redis::connection('notify_cache')->subscribe($pattern,function ($channel){
// 订阅键过期事件
Log::info('-----notify-----'.$channel);
$key_type = str_before($channel,':');
switch ($key_type) {
case 'NOTIFY_CONFIRM':
$id = str_after($channel,':'); // 取出学员ID
$client = Client::find($id);
if ($client) {
//业务逻辑
}
}
break;
default:
break;
}
});
PS:之所以用这种方式 不想每段时间是去做扫表操作。