httpserver = new \swoole\http\server($config['host'], $config['port']); $this->httpserver->set($config['sets']); $this->config = $config; $this->redisconfig = GlobConfigs::getKey('redis'); $this->httpserver->account = new \swoole\Atomic(); $this->httpserver->taskWorkingNum = new \swoole\Atomic(); $this->httpserver->on('request', array($this, 'OnRequest')); $this->httpserver->on('WorkerStart', array($this, 'onWorkerStart')); $this->httpserver->on('task', array($this, 'onTask')); $this->httpserver->on('finish', array($this, 'onFinish')); } public function onWorkerStart($serv, $worker_id) { ModelBase::init(); $this->TaskSqlQueue = new \SplQueue(); Swoole\Timer::tick(1000, function () { $this->TimeWork(); }); Swoole\Timer::tick(1000, function () { $this->TaskSQlToRedis(); }); if ($serv->worker_id == 0) { Swoole\Timer::tick(60000, function () { $this->logRunStatus(); }); } $this->getFanshui(); } private function logRunStatus() { echo date('Y-m-d H:i:s') . " 总请求数:" . $this->httpserver->account->get() . ' 运行任务数:' . $this->httpserver->taskWorkingNum->get(); echo ' work_id:' . $this->httpserver->worker_id . " 内存使用量:" . (memory_get_usage() / 1000) . 'k 峰值:' . (memory_get_peak_usage() / 1000) . "k\n"; } private function getRedis() { if (time() - $this->redisTime <= 60 * 30) { if ($this->redis) { return $this->redis; } } else { if ($this->redis) { $this->redis->close(); } } $this->redis = new \redis(); $ret = $this->redis->connect($this->redisconfig['host'], $this->redisconfig['port']); if (!$ret) { $this->redis = false; throw new \Exception("连接redis失败 " . date("Y-m-d H:i:s"), 108); return; } if (!$this->redis->auth($this->redisconfig['passwd'])) { throw new \Exception("redis auth 失败 " . date("Y-m-d H:i:s"), 109); return; } $this->redis->select($this->redisconfig['db']); $this->redisTime = time(); return $this->redis; } //全部结算 结束要改结算和比赛状态 private function doSettelement($paras) { $begin = microtime(true); $this->userMoneyTotal = []; try { list($order_ids, $bettype, $settype, $game_code, $match_id, $change_status, $is_manual) = $this->requestpara($paras); if (!$this->DataPre($order_ids, $bettype, $settype, $game_code, $match_id, $change_status, $is_manual)) { $this->cgStatus($game_code, $match_id, $change_status); goto LABDOLAST; //throw new \Exception('没找到订单信息', 110); } $this->UndoSettlement(); while (true) { $order_id = trim(array_shift($order_ids)); if (empty($order_id)) { break; } $nowBuyDatasMainModel = $this->PDatas['Money_buy_Orders_Array'][$order_id]; if ($nowBuyDatasMainModel->status != 1) { // continue; } $account_indent = $nowBuyDatasMainModel->account_identity; $paras = [ 'type' => 'Settelement', 'bet_type' => $bettype, 'set_type' => $settype, 'order_id' => $order_id, 'game_code' => $game_code, 'match_id' => $match_id, 'simplexData' => $nowBuyDatasMainModel, 'matchDatas' => $this->PDatas['Money_buy_Match_array'][$order_id], 'settelementMidDataID' => isset($this->PDatas['settlement_middle_detail_array'][$bettype][$order_id]) ? $this->PDatas['settlement_middle_detail_array'][$bettype][$order_id]->id : 0, 'account' => $this->PDatas['account_map_array'][$account_indent]->account, 'money_prize' => isset($this->PDatas['money_prize_map'][$order_id]) ? $this->PDatas['money_prize_map'][$order_id]->id : 0 ]; if ($bettype == 1) { $this->singOrder($paras); $this->cgStatus($game_code, $match_id, $change_status); } else { $this->ChuanOrder($paras); $this->cgStatus($game_code, $match_id, $change_status); } $this->UserTotalMoneySql(); } LABDOLAST: //$this->cgStatus($game_code, $match_id, $change_status); } catch (\Exception $e) { $this->PDatas = []; //$data = Response::generate('', $e->getCode(), '', $e->getMessage() . '--' . $e->getFile() . '--' . $e->getLine()); $data = Response::generate('', $e->getCode(), '', $e->getMessage() . '--' . $e->getLine()); echo $data . "\n"; } $this->timeCost($begin); } private function requestpara($paras) { $this->PDatas = []; $paras = json_decode($paras, true); $idoarr = $paras['ids']; $order_ids = array_map(function ($i) { return strval($i); }, $idoarr); $bettype = isset($paras['bettype']) ? $paras['bettype'] : 0; //$settype = isset($paras['settype']) ? $paras['settype'] : 0; $settype = 2; $game_code = isset($paras['game_code']) ? $paras['game_code'] : ''; $match_id = isset($paras['match_id']) ? $paras['match_id'] : 0; $change_status = isset($paras['change_status']) ? $paras['change_status'] : 0; $is_manual = isset($paras['is_manual']) ? intval($paras['is_manual']) : 0; if (intval($match_id) <= 0) { throw new \Exception('赛事ID不能为空!', 100); return; } if (empty($game_code)) { throw new \Exception('赛事类型不能为空!', 101); } if (!in_array($bettype, [1, 2])) { throw new \Exception('订单类型参数错误!', 102); } if (!in_array($settype, [1, 2])) { throw new \Exception('结算参数错误', 103); } $this->PDatas['bettype'] = $bettype; $this->PDatas['settype'] = $settype; $this->PDatas['game_code'] = $game_code; $this->PDatas['match_id'] = $match_id; $ret = [$order_ids, $bettype, $settype, $game_code, $match_id, $change_status, $is_manual]; return $ret; } //重结算时,要先扣掉先前发的钱 private function UndoSettlement() { if (empty($this->PDatas['settlement_middle_detail_array'])) { return true; } $bet_type = $this->GP('bettype'); $nowArray = $this->PDatas['settlement_middle_detail_array'][$bet_type]; $ids = []; $userMonsys = []; foreach ($nowArray as $order => $val) { $money = abs(floatval($val->money)); if (100 * $money > 1) { $acc = $val->account_identity; $userMonsys[$acc] = isset($userMonsys[$acc]) ? $userMonsys[$acc] + $money : $money; $ids[] = $order; } } //一个用户多次变化金额时,合并为一条语名,减少锁表的可能性 if (empty($userMonsys)) { return true; } foreach ($userMonsys as $account => $money) { $sql = "update account_detailed set cash=cash-$money where identity='$account' "; $this->PushSqlToArray($sql); } if (count($ids) <= 0) { return true; } $ids_array = array_map(function ($i) { return "'$i'"; }, $ids); $ids_array = implode(",", $ids_array); unset($ids_array_0); $sql = "update settlement_middle_detail set money=0 where order_id in($ids_array) and bet_type=$bet_type "; $this->PushSqlToArray($sql); return true; } //得么一个临时变量 private function GP($name) { return $this->PDatas[$name]; } private function TimeWork() { $this->httpserver->taskWorkingNum->add(); try { $ret = $this->getRedis()->rpop(self::TASKQNUM); if (!empty($ret)) { echo date("Y-m-d H:i:s") . " 开始处理:" . $ret . "\n"; $this->httpserver->account->add(); $this->doSettelement($ret); } } catch (\Exception $e) { echo "Error: " . $e->getMessage() . '--' . $e->getFile() . '--' . $e->getLine() . "\n"; } $this->httpserver->taskWorkingNum->sub(); } private function cgStatus($game_code, $match_id, $change_status) { if (!$change_status) { return; } $table1 = "st_" . $game_code . "_result"; $table2 = "st_" . $game_code . "_competition"; $this->PushSqlToArray("update $table1 set status=3 where match_id=$match_id "); $this->PushSqlToArray("update $table2 set status=3 where id=$match_id "); unset($table1, $table2); } private function timeCost($begin, $now = 0, $txt = '') { if ($now == 0) { $now = microtime(true); } $cost = $now - $begin; echo " Cost: $txt " . $cost . " 秒\n"; } private function TaskSQlToRedis() { if ($this->TaskSqlQueue->isEmpty()) { return; } $this->sqltoRedisqueue(); } /** * 单式注单结算 * @param mixed $order_id 注单ID */ private function singOrder($task) { $matchDatas = $task['matchDatas']; $simplexData = $task['simplexData']; $account_identity = $simplexData->account_identity; $bet_type = $task['bet_type']; $order_id = $task['order_id']; $match_id = $task['match_id']; $game_code = $task['game_code']; $account = $task['account']; $money_prize = $task['money_prize']; foreach ($matchDatas as $val) { if (!in_array($val->result, [-1, 1, 2, 3, 4])) { throw new \Exception('match比赛结果异常或还没有输赢结果->' . $val->id, 104); } } if (empty($this->SettlementBaseObj)) { $settlementBase = $this->SettlementBaseObj = new SettlementBase(); } else { $settlementBase = $this->SettlementBaseObj; } $returnMoney = 0; $oddsResult = []; if ($simplexData->status == 1) { foreach ($matchDatas as $k => $v) { if ($v->result == -1) { continue; } $oddsResult[0]['winOrLose'] = $v->result; $oddsResult[0]['odds'] = $v->odds; $getReturnMoney = $settlementBase->stringOdds($oddsResult); if ($v->result == 2) { //返水钱扣掉 $pv = $this->gethuishuilv(); $getReturnMoney['returnMoney'] = 1 - $pv; } $returnMoney += $getReturnMoney['returnMoney'] * $v->bet_money; } } else { $returnMoney = $simplexData->money; } $returnMoney = floatPointDigit($returnMoney - $simplexData->money * $this->fanshui); //$returnMoney = sprintf("%.2f", substr(sprintf("%.3f", $returnMoney), 0, -1)); // 判断盈亏 1 赢 2 输 3 平 $game_status = $returnMoney > $simplexData->money ? 1 : ($returnMoney == $simplexData->money ? 3 : 2); // 修改投注表状态及盈亏 $this->PushSqlToArray(["update money_buy_simplex set settle_status=2, game_status=$game_status,gain_money=$returnMoney where order_id='$order_id' "]); $this->userMoneyTotal[$account_identity] = isset($this->userMoneyTotal[$account_identity]) ? $this->userMoneyTotal[$account_identity] + $returnMoney : $returnMoney; $this->WriteOrAddSettlement($game_code, $match_id, $bet_type, $order_id, $account_identity, $returnMoney); $this->insertData( $order_id, $returnMoney, $account_identity, 1, $game_code, $simplexData->info_identity, $simplexData->money, $match_id, $account, $money_prize ); } private function WriteOrAddSettlement($game_code, $match_id, $bet_type, $order_id, $account_ident, $money) { if (intval($money * 1000) < 10) { return; } if (isset($this->PDatas['settlement_middle_detail_array'][$bet_type][$order_id])) { $this->PushSqlToArray("update settlement_middle_detail set money=$money where game_code='$game_code' and bet_type=$bet_type and order_id='$order_id' "); } else { $this->PushSqlToArray("insert into settlement_middle_detail(game_code,match_id,account_identity,bet_type,order_id,money) values('$game_code','$match_id','$account_ident',$bet_type,'$order_id',$money)"); } return true; } private function PushSqlToArray($cmdArray) { if (is_string($cmdArray)) { $this->TaskSqlQueue->enqueue($cmdArray); } else { foreach ($cmdArray as $sql) { $this->TaskSqlQueue->enqueue($sql); } } } private function ChuanOrder($task) { $matchDatas = $task['matchDatas']; $simplexData = $task['simplexData']; $account_identity = $simplexData->account_identity; $bet_type = $task['bet_type']; $order_id = $task['order_id']; $match_id = $task['match_id']; $game_code = $task['game_code']; $account = $task['account']; $money_prize = $task['money_prize']; //如果有一条为输的,订单直接为输了 foreach ($matchDatas as $val) { if ($val->result == -1) { $this->PushSqlToArray("update money_buy_str set wait_match_num=0, prize_note=0, game_status=3, settle_status=2, gain_money=0,settlement_time='" . date('Y-m-d H:i:s') . "' where order_id='$order_id' "); return; } } foreach ($matchDatas as $val) { if (!in_array($val->result, [1, 2, 3, 4])) { throw new \Exception('match比赛结果异常或还没有输赢结果->' . $val->id, 105); } } $matchModels = $matchDatas; if (count($matchModels) <= 0) { throw new \Exception('match 数据异常-' . $order_id, 106); } if (empty($this->SettlementBaseObj)) { $settlementBase = $this->SettlementBaseObj = new SettlementBase(); } else { $settlementBase = $this->SettlementBaseObj; } $newTime = date('Y-m-d H:i:s'); if ($simplexData->status == 1) { $in_array = []; foreach ($matchModels as $val) { if (!in_array($val->result, [-1, 1, 2, 3, 4])) { throw new \Exception('match 比赛结果异常或还没有输赢结果->' . $val->id, 107); } if ($val->result == -1) { $this->PushSqlToArray("update money_buy_str set wait_match_num=0, prize_note=0, game_status=3, settle_status=2, gain_money=0,settlement_time='" . date('Y-m-d H:i:s') . "' where order_id='$order_id' "); return true; } $in_array[] = ['odds' => $val->odds, 'winOrLose' => $val->result]; } $chuanNum = intval(substr($simplexData->str_type, 0, 1)); $lasPeilv = $settlementBase->stringComputing([$in_array, $chuanNum]); $money_s = floatPointDigit($simplexData->money * $lasPeilv); } else { $money_s = $simplexData->money; } $money = floatPointDigit($money_s - $simplexData->money * $this->fanshui); $this->PushSqlToArray(" update money_buy_str set settle_status=2 , game_status=1 , settlement_time='$newTime' , gain_money=$money where order_id = '$order_id'"); $this->WriteOrAddSettlement($game_code, $match_id, $bet_type, $order_id, $account_identity, $money); $useraccident = $simplexData->account_identity; $this->userMoneyTotal[$useraccident] = isset($this->userMoneyTotal[$useraccident]) ? $this->userMoneyTotal[$useraccident] + $money : $money; $this->insertData($order_id, $money, $useraccident, 2, $game_code, $simplexData->info_identity, $money, $match_id, $account, $money_prize); return true; } /** * 结算数据填入 * @param mixed $order_id 注单ID * @param mixed $returnMoney 返现金额 * @param mixed $account_identity 用户ID * @param mixed $type 1单式 2串式 * @param mixed $game_name 游戏名(zq,lq) * @param mixed $buy_identity 游戏投注id * @param mixed $money 投注金额 * @param mixed $match_id 赛场ID */ private function insertData($order_id, $returnMoney, $account_identity, $type, $game_name, $buy_identity, $money, $match_id = 0, $account = '', $money_prizeID = 0) { // 添加流水记录 $info_identity = UUID(); $money_time = date('Y-m-d H:i:s', time()); $trade_desc = $type == 1 ? '单式投注订单回款' : '串式投注订单回款'; $reason = $type == 1 ? '单式投注订单回款' : '串式投注订单回款'; //用于记录用户余额的数据 if (!isset($this->PDatas['account_mash'][$account_identity])) { $this->PDatas['account_mash'][$account_identity] = $this->PDatas['account_indentity_map_array'][$account_identity]->cash; } $this->PDatas['account_mash'][$account_identity] = $this->PDatas['account_mash'][$account_identity] + $returnMoney; $user_money_cash = $this->PDatas['account_mash'][$account_identity]; if (isset($this->PDatas['money_detail_array'][$order_id])) { $sql = "update money_details set money=$returnMoney,money_cash=$user_money_cash where account_identity='$account_identity' and trade_id='$order_id' and trade_type=4 "; } else { $sql = "insert into money_details(info_identity,trade_id,account_name,account_identity,money,money_time,money_type,money_cash,trade_type,trade_desc,reason,sysetem_user,status) values("; $sql .= "'$info_identity','$order_id','$account','$account_identity',$returnMoney,'$money_time',1,$user_money_cash,4,'$trade_desc','$reason','系统',1)"; } $this->PushSqlToArray($sql); // 修改用余额 在外面合并了,不需要了 //$this->PushSqlToArray("update account_detailed set available_cash=available_cash+$money,cash=cash+$money where account_identity='$account_identity' "); // 新增用户中奖信息 $content = $type == 1 ? '您的单式投注订单' . $order_id . '于' . $money_time . '成功回款' . $returnMoney . '该次投注流程结束,如有疑问请联系客服' : '您的串式投注订单' . $order_id . '于' . $money_time . '成功回款' . $returnMoney . '该次投注流程结束,如有疑问请联系客服'; $sql = "insert into account_news(identity,account_identity,title,content,details,write_time,read_status,type) values "; $sql .= "('$info_identity','$account_identity','投注订单回款通知','$content','$content','$money_time',-1,1)"; $this->PushSqlToArray($sql); // 新增中奖记录表 $table = 'money_prize'; if ($money_prizeID) { $this->PushSqlToArray("update $table set money=$money,prize_money=$returnMoney, get_money= $returnMoney - $money where id=$money_prizeID"); } else { $sql = "insert into $table (info_identity,order_id,account_identity,account_name,game_name,buy_identity,money,money_time,status,prize_money,get_money) values "; $sql .= "('$info_identity','$order_id','$account_identity','$account','$game_name','$buy_identity',$money,'$money_time',1,$returnMoney,$returnMoney - $money)"; $this->PushSqlToArray($sql); } return true; } //对同一用户账号资金变化更改合并操作,减少锁表可能 private function UserTotalMoneySql() { if (!empty($this->userMoneyTotal)) { foreach ($this->userMoneyTotal as $account_identity => $money) { $this->PushSqlToArray("update account_detailed set available_cash=available_cash+$money,cash=cash+$money where account_identity='$account_identity' "); } } } //数据预批量获取 private function DataPre($order_ids, $bettype, $settype, $game_code, $match_id, $change_status, $is_manual = 0) { if ($bettype == 1) { $moneytable = 'money_buy_simplex'; //$ret = DB::table('money_buy_simplex')->where(['game_code' => $game_code, 'match_id' => $match_id, 'is_manual' => $is_manual])->whereIn('order_id', $order_ids)->get(); $tmpwhere = [['game_code', '=', $game_code], ['match_id', '=', $match_id], ['is_manual', '=', $is_manual], ['roll_ratify', '>=', 0]]; $ret = DB::table('money_buy_simplex')->where($tmpwhere)->whereIn('order_id', $order_ids)->get(); } else { $moneytable = 'money_buy_str'; $ret = DB::table('money_buy_str')->whereIn('order_id', $order_ids)->get(); } if (empty($ret) || count($ret) <= 0) { return false; } foreach ($ret as $val) { $this->PDatas['Money_buy_Orders_Array'][$val->order_id] = $val; $orderarr[] = $val->order_id; $userindentys[] = $val->account_identity; } $userindentys = array_unique($userindentys); if ($bettype == 1) { $ret = DB::table('money_buy_match')->where(['game_code' => $game_code, 'match_id' => $match_id, 'bet_type' => 1])->whereIn('order_id', $orderarr)->get(); } else { $ret = DB::table('money_buy_match')->where(['game_code' => $game_code, 'bet_type' => 2])->whereIn('order_id', $orderarr)->get(); } foreach ($ret as $val) { $this->PDatas['Money_buy_Match_array'][$val->order_id][] = $val; } $ret = DB::table('account_detailed')->whereIn('account_identity', $userindentys)->get(); foreach ($ret as $val) { $this->PDatas['account_indentity_map_array'][$val->account_identity] = $val; } $ret = DB::table('account')->whereIn('identity', $userindentys)->get(); foreach ($ret as $val) { $this->PDatas['account_map_array'][$val->identity] = $val; } if ($settype == 2) { $ret = DB::table('settlement_middle_detail')->where(['game_code' => $game_code, 'match_id' => $match_id])->whereIn('order_id', $order_ids)->get(); if ($ret) { foreach ($ret as $val) { $this->PDatas['settlement_middle_detail_array'][$val->bet_type][$val->order_id] = $val; } } $order_str_1 = array_map(function ($item) { return "'$item'"; }, $orderarr); $order_str = implode(",", $order_str_1); if ($bettype == 1) { $sql_tmp = "update $moneytable set settle_status=1, gain_money=0, game_status=0 where game_code='$game_code' and match_id=$match_id and status=1 and order_id in ($order_str) "; } else { $sql_tmp = "update $moneytable set settle_status=1, gain_money=0 where order_id in ($order_str) "; } $this->PushSqlToArray($sql_tmp); } $ret = DB::table('money_prize')->whereIn('order_id', $order_ids)->where('money', '>', 0.01)->get(); if ($ret) { foreach ($ret as $val) { $this->PDatas['money_prize_map'][$val->order_id] = $val; } } $ret = DB::table('money_details')->whereIn('account_identity', $userindentys)->where([['money_time', '>=', date("Y-m-d", time() - 86400 * 90) . ' 00:00:00'], ['trade_type', '=', 4]])->whereIn('trade_id', $order_ids)->get(); if ($ret) { foreach ($ret as $val) { $this->PDatas['money_detail_array'][$val->trade_id] = $val; } } return true; } private function gethuishuilv() { $key = "HUISHUILV"; $rv = $this->getRedis()->get($key); if ($rv) { return floatval($rv); } $rv = DB::table('setinfo')->where('identity', '1000')->first(); if ($rv) { $pl = floatval(trim($rv->infocontent)); $this->getRedis()->setex($key, 300, $pl); return $pl; } return 0; } private function sqltoRedisqueue() { $sqlQueue = $this->TaskSqlQueue; $redis = $this->getRedis(); $i = 1; $maxStep = 10000; $sql = ''; if (!$sqlQueue->isEmpty()) { $redis->pipeline(); while ($i < $maxStep) { if (!$sqlQueue->isEmpty()) { $sql = $sqlQueue->dequeue(); if (empty($sql)) { break; } $redis->lpush(self::SQLKEY, $sql); } $i++; } $redis->exec(); } unset($sqlQueue, $sql, $i, $maxStep, $ret); return; } public function OnRequest($request, $response) { } public function onTask($serv, $task) { } public function onFinish($serv, int $task_id, $data) { } //得到返水的比例 public function getFanshui() { $ret = (new SetinfoModel())->getInfo(1001); if (is_array($ret)) { $val = floatval($ret['infocontent']); $this->fanshui = $val; return $val; } } public function start() { $this->httpserver->start(); } }