修改reids配置文件打开订阅销毁事件
# 原配置: notify-keyspace-events "" # 更改为: notify-keyspace-events "Ex"
添加TP5.1 Redis订阅处理函数
<?php namespace app\common\command; use think\facade\Cache; use think\console\Command; use think\console\Input; use think\console\Output; use think\Db; use think\Exception; class SetNextnum extends Command { protected function configure() { parent::configure(); // TODO: Change the autogenerated stub $this->setName('timeout')->setDescription('Cancel Timeout Order'); } protected function execute(Input $input, Output $output) { $this->getKey(); $output->writeln("ok"); } public function getKey() { // socket流的超时时间 -1禁用超时 ini_set('default_socket_timeout', -1); // cli模式下,开启数据库断开重连,防止脚本运行一段时间后数据库断开连接 $dbConfig = config('database.'); $dbConfig['break_reconnect'] = true; Db::init($dbConfig); // 返回Redis句柄对象 $redis = Cache::store('redis')->handler(); // Redis 订阅监听过期事件 $redis->psubscribe(array('__keyevent@0__:expired'), 'app\common\command\SetNextnum::keyCallback'); // 回调必须写绝对路径 要不然会报错 } // key过期回调 public static function keyCallback($redis, $pattern, $channel, $message) { $url = config('app.app_is_product') ? 'https://api.manyideacloud.com/hudong.php/Hudongsinglegame/nextNumback' : 'https://apitest.manyideacloud.com/hudong.php/Hudongsinglegame/nextNumback'; // redis key 示例: openid==1|sdkijhfkjsdhakhkjhx if (strpos($message, 'openid=') !== false) { $str = substr($message, strlen('openid=')); list($roundId, $openid) = explode('|', $str); $scriptMsg = ''; $logMsg = ''; $curlPost = ['id' => $roundId, 'openid' => $openid]; $scriptMsg .= "自动清除卡在队列中的openid:" . $roundId . "|" . $openid; $curl = curl_init(); //设置提交的url curl_setopt($curl, CURLOPT_URL, $url); //设置头文件的信息作为数据流输出 curl_setopt($curl, CURLOPT_HEADER, 0); //设置获取的信息以文件流的形式返回,而不是直接输出。 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //设置post方式提交 curl_setopt($curl, CURLOPT_POST, 1); //设置参数 curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost); //执行命令 $data = curl_exec($curl); //关闭URL请求 curl_close($curl); //获得数据并返回 self::timeoutOrderWriteLog($scriptMsg); // 写入日志 echo $scriptMsg; // 脚本消息提示 } } /** * 取消订单写入日志 * @param string $data 写入的信息 */ public static function timeoutOrderWriteLog($data) { //设置路径目录信息 $datefile = date('Ym'); $url = './log/' . $datefile . '/timeout-order.txt'; // 项目根目录,而非public目录 $dir_name = dirname($url); //目录不存在就创建 if (!file_exists($dir_name)) { //iconv防止中文名乱码 $res = mkdir(iconv("UTF-8", "GBK", $dir_name), 0777, true); } $fp = fopen($url, "a");//打开文件资源通道 不存在则自动创建 fwrite($fp, date("Y-m-d H:i:s") . var_export($data, true) . "\r\n");//写入文件 fclose($fp);//关闭资源通道 } }
在command.php中添加函数
return [ //自动设置下一位 'SetNextnum' => 'app\common\command\SetNextnum' ];
开启函数
php think SetNextnum
后台运行函数
nphup php think SetNextnum &2>&1 &
Linux 查看后台任务
jobs //关闭任务 kill %num