setUser(); $pid = posix_getpid(); //连接redis $this->connectionRedis(); $remainNum = $this->redisClient->lLen("$redisKey"); if($remainNum >$alertNum){ $mailService = new MailService(); $res = $mailService->send('leo',"{$alertName}自动升级进程数","剩余数量$remainNum,主动清理程序",[],[['mail'=>'2990412861@qq.com','name'=>'leo.xie']]); //自动升级进程数 $normalPidList = Cache::get("{$redisKey}_pop_program"); is_array($normalPidList)?$normalPidList[] = $pid:$normalPidList = [$pid]; Cache::set("{$redisKey}_pop_program",$normalPidList); }else{ $normalPidList = Cache::get("{$redisKey}_pop_program"); if(is_array($normalPidList) && count($normalPidList) > 1){ //自动降级进程数 foreach($normalPidList as $itemPid){ Log::record("进程kill:".$itemPid."\n"); posix_kill($itemPid, SIGKILL); } Cache::rm("{$redisKey}_pop_program"); $mailService = new MailService(); $res = $mailService->send('leo',"{$alertName}自动降级进程数","剩余数量$remainNum,主动清理程序",[],[['mail'=>'2990412861@qq.com','name'=>'leo.xie']]); }elseif(!empty($normalPidList) ){ die('['.$date.']有正在执行中的程序'); } Cache::set("{$redisKey}_pop_program",[$pid]); } while(true){ //有时候进程没有杀掉,做一次自我修复机制 $curPid = posix_getpid(); $normalPidList = Cache::get("{$redisKey}_pop_program"); if(!is_array($normalPidList) || !in_array($curPid, $normalPidList)){ Log::record('异常中断'.$curPid); exit(0); } $requestJson = $this->redisClient->lPop("$redisKey"); if(empty($requestJson)){ sleep(10); try{ $this->redisClient->close(); }catch (\Exception $ex){ //nothing to do... } $this->connectionRedis(); continue; } $requestArr = @json_decode($requestJson,true); if(empty($requestArr)){ continue; } try{ $return = $this->mainFunc($requestArr); if($return === false){ //给三次重试机会 $requestArr['__times__'] = isset($requestArr['__times__'])?$requestArr['__times__']+1:1; $requestArr['__times__'] < 4?$this->redisClient->lpush("$redisKey", json_encode($requestArr)):""; } } catch (\Exception $ex){ $mailService = new MailService(); $mailService->send('leo',"{$alertName}出队异常","",$ex->getMessage(),[['mail'=>'2990412861@qq.com','name'=>'leo.xie']]); } } }catch(\Exception $ex){ //自动降级进程数 echo $ex->getMessage()."\n"; echo "cache\n"; Cache::rm("{$redisKey}_pop_program"); exit(0); } } /** * 连接远程的redis */ private function connectionRedis(){ $this->redisClient = new \Redis(); $this->redisClient->connect('47.97.187.118', 6379); $this->redisClient->auth('gudong-hz'); } //设置运行的用户 private function setUser($name='www') { $maxPid = posix_getpid(); $pid = pcntl_fork(); if ($pid != 0) { posix_kill($maxPid, SIGKILL); } if (empty($name)) { return false; } $user = posix_getpwnam($name); if ($user) { $uid = $user['uid']; $gid = $user['gid']; $result = posix_setuid($uid); posix_setgid($gid); } return $result; } }