| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412 |
- <?php
- /**
- * Created by PhpStorm.
- * User: Administrator
- * Date: 2019/6/26
- * Time: 12:03
- */
- namespace datainf\logic;
- use App\Lib\ModelBase;
- use App\Http\Response\Response;
- use App\Logic\WinfailLogic;
- use datainf\lib\GlobConfigs;
- use Illuminate\Database\Capsule\Manager as DB;
- use swoole;
- use App\Logic\SettelementLogic;
- class HttpServerSettelement
- {
- private $httpserver;
- private $config;
- private $dbpooleconfig = [];
- private $redisonfig = [];
- const SQLKEY = 'ALLSQLKEY';
- private $TaskSqlArray = [];
- private $TaskSqlArrayCopy = [];
- use SettelementLogic;
- public function __construct($config)
- {
- $this->httpserver = new \swoole\http\server($config['host'], $config['port']);
- $this->httpserver->set($config['sets']);
- $this->config = $config;
- $this->dbpooleconfig = GlobConfigs::getKey('pgsqlpoole');
- $this->redisonfig = GlobConfigs::getKey('redis');
- $taskWorkingNum = new \swoole\Atomic();
- $this->httpserver->taskWorkingNum = $taskWorkingNum;
- $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)
- {
- $name = $serv->taskworker ? 'Task_' : 'Worker_';
- $name = 'Settelement_' . $name . ($serv->worker_id < 10 ? '0' . $serv->worker_id : $serv->worker_id);
- swoole_set_process_name($name);
- $GLOBALS['model'] = '';
- $GLOBALS['modeltime'] = 0;
- if (!$serv->taskworker) {
- $this->InitDb();
- } else {
- $obj = $this;
- Swoole\Timer::tick(1000, function ($id) use ($obj) {
- $obj->TaskSQlToRedis();
- });
- }
- if ($worker_id == 0) {
- $obj = $this;
- Swoole\Timer::tick(500, function ($id) use ($obj) {
- $obj->BatchSqlRedisToDB();
- });
- }
- }
- public function OnRequest($request, $response)
- {
- $response->header('Content-Type', 'text/html; charset=utf-8');
- $response->header('Server', 'DataInfaceServer');
- $paras = array_merge(['request_time' => date("H:i:s")], !empty($request->get) ? $request->get : [], !empty($request->post) ? $request->post : []);
- $request_uri = substr($request->server['request_uri'], 1);
- $urls = ['WinFail', 'Settelement'];
- if (!in_array($request_uri, $urls)) {
- $data = Response::generate('', 0, '', '无效的url');
- $response->end($data);
- return;
- }
- if ($this->httpserver->taskWorkingNum->get() > 0) {
- $data = Response::generate('', 9, '', '还有未完成任务请稍等...');
- $response->end($data);
- return;
- }
- $check_token = true;
- if ($check_token) {
- $token = isset($paras['token']) ? $paras['token'] : '';
- if (empty($token) || empty($this->Tokencheck($token))) {
- $data = Response::generate('', 6, '', '安全验证失败!');
- $response->end($data);
- return;
- }
- }
- if ($request_uri == 'WinFail') {
- return $this->doWinFailse($request, $response, $paras);
- }
- if ($request_uri == 'Settelement') {
- return $this->doSettelement($request, $response, $paras);
- }
- return;
- }
- public function onTask($serv, $task)
- {
- $this->httpserver->taskWorkingNum->add();
- if ($task['type'] == 'doWinFailse') {
- $this->Task_winfalse($serv, $task);
- }
- if ($task['type'] == 'Settelement') {
- $this->Task_Settelement($serv, $task);
- }
- $this->httpserver->taskWorkingNum->sub();
- }
- private function Tokencheck($token)
- {
- $tokenvel = DB::table('system_user')->where(['token' => $token])->first();
- return $tokenvel;
- }
- //胜负计算
- private function doWinFailse($request, $response, $paras)
- {
- $logic_obj = new WinfailLogic();
- $notice = isset($paras['noticeid']) ? $paras['noticeid'] : 0;
- $id = intval($notice);
- try {
- $noticeModel = $logic_obj->getNoticeDate($id);
- $result = $logic_obj->getCompResult($noticeModel->game_code, $noticeModel->match_id);
- $moneySimples = $logic_obj->getSimplexData($noticeModel->game_code, $noticeModel->match_id);
- $matchs_1 = $logic_obj->getMatchRecords($noticeModel->game_code, $noticeModel->match_id, 1);
- $matchs_2 = $logic_obj->getMatchRecords($noticeModel->game_code, $noticeModel->match_id, 2);
- $match_firstModel = isset($matchs_1['0']) ? $matchs_1['0'] : (isset($matchs_2['0']) ? $matchs_2['0'] : false);
- if (!$match_firstModel) {
- throw new \Exception('无数据异常-1!');
- return true;
- }
- $gjModel = $logic_obj->getGjDatas($match_firstModel);
- if (count($matchs_1) > 0 && count($moneySimples) <= 0) {
- throw new \Exception('数据异常-2!');
- }
- if (strtolower($match_firstModel->p_code) == 'gj') {
- if (empty($gjModel)) {
- throw new \Exception("没有冠军数据数据--match_id" . $noticeModel->match_id);
- }
- $result = [$gjModel];
- }
- if (!empty($matchs_1)) {
- while (true) {
- if ($this->httpserver->taskWorkingNum->get() > intval($this->config['sets']['task_worker_num'])) {
- co::sleep(50);
- } else {
- $now = array_shift($matchs_1);
- if (empty($now)) {
- break;
- }
- $paras = ['type' => 'doWinFailse', 'stype' => 1, 'matchModel' => $now, 'result' => $result, 'moneySimple' => $moneySimples[$now->batch_id][$now->match_id]];
- $this->onTask($this->httpserver, $paras);
- }
- }
- }
- if (!empty($matchs_2)) {
- while (true) {
- if ($this->httpserver->taskWorkingNum->get() > intval($this->config['sets']['task_worker_num'])) {
- co::sleep(50);
- } else {
- $now = array_shift($matchs_2);
- if (empty($now)) {
- break;
- }
- $paras = ['type' => 'doWinFailse', 'stype' => 1, 'matchModel' => $now, 'result' => $result, 'moneySimple' => $moneySimples[$now->batch_id][$now->match_id]];
- $this->onTask($this->httpserver, $paras);
- }
- }
- }
- unset($logic_obj, $noticeModel, $AdapterObj, $result, $moneySimples, $matchs_1, $matchs_2, $RefClass);
- $this->httpserver->taskWorkingNum->add();
- $this->sqltoRedisqueue($this->TaskSqlArray);
- $this->httpserver->taskWorkingNum->sub();
- $data = Response::generate('', 1, ['cost' => (microtime(true) - $request->server['request_time_float'])], 'succes ');
- $response->end($data);
- return;
- } catch (\Exception $e) {
- unset($logic_obj);
- $data = Response::generate('', 10, '', $e->getMessage() . '--' . $e->getFile() . '--' . $e->getLine());
- $response->end($data);
- return;
- }
- return;
- }
- /////
- private function Task_winfalse($serv, $task)
- {
- try {
- $moneyBuy = $task['moneySimple'];
- $matchModel = $task['matchModel'];
- $logic = WinfailLogic::getInstance();
- $AdapterObj = $logic->getAdapterObj($matchModel->game_code);
- $RefClass = new \ReflectionClass($AdapterObj);
- //如果手动更改了结果,就用更改后的结果,否则用默认的结果
- if ($matchModel->bet_type == 1 && $moneyBuy['result_flag'] == 1) {
- $now_result = [json_decode($moneyBuy['single_result'])];
- } else {
- foreach ($task['result'] as $key => $val) {
- $now_result[] = $val;
- }
- }
- $fun1 = $matchModel->odds_code;
- $fun2 = $matchModel->p_code;
- $winorfalsedef = ['result' => 2, 'matchResult' => 'noRuleOrError'];
- try {
- if ($RefClass->hasMethod($fun1)) {
- $winorfalse = $AdapterObj->$fun1($matchModel, $now_result, []);
- } elseif ($RefClass->hasMethod($fun2)) {
- $winorfalse = $AdapterObj->$fun2($matchModel, $now_result, []);
- }
- } catch (\Exception $e) {
- }
- if (!isset($winorfalse['result']) || !isset($winorfalse['matchResult']) || !in_array($winorfalse['result'], [-1, 1, 2, 3, 4])) {
- $winorfalse = $winorfalsedef;
- }
- $sql_1 = $this->makesql_up_buymatch_winorfalse($matchModel->id, $winorfalse['result'], date("Y-m-d H:i:s"), $winorfalse['matchResult']);
- $gs_val = ($winorfalse['result'] == 1) ? 1 : ($winorfalse['result'] == -1 ? 2 : 3);
- if ($matchModel->bet_type == 1) {
- $sql_2 = "update money_buy_simplex set game_status=$gs_val where batch_id='$matchModel->batch_id' and match_id='$matchModel->match_id' and game_code='$matchModel->game_code' ";
- } else {
- $sql_2 = "update money_buy_str set wait_match_num=wait_match_num-1 where batch_id='$matchModel->batch_id' ";
- }
- $this->PushSqlToArray([$sql_1, $sql_2]);
- } catch (\Exception $e) {
- echo $e->getMessage() . '--' . $e->getFile() . '--' . $e->getLine() . "\n";
- }
- return true;
- }
- //生成更新sql;
- private function makesql_up_buymatch_winorfalse($id, $result, $utime, $matchResult = '')
- {
- $matchResult = str_replace(";", ";", $matchResult);
- $sql = "update money_buy_match set result=$result, utime='$utime',matchResult='$matchResult' where id=$id ";
- return $sql;
- }
- /*
- private function DbpooleClient($sqlArray = [])
- {
- go(function () use ($sqlArray) {
- $client = new \swoole_client(SWOOLE_SOCK_TCP);
- if (!$client->connect('127.0.0.1', $this->dbpooleconfig['poole_port'], 1)) {
- return false;
- }
- foreach ($sqlArray as $val) {
- $cmds[] = $val;
- }
- $this->sqltoRedisqueue($cmds);
- $client->close();
- });
- }
- */
- private function PushSqlToArray($cmdArray)
- {
- if (is_string($cmdArray)) {
- array_push($this->TaskSqlArray, $cmdArray);
- } else {
- foreach ($cmdArray as $sql) {
- array_push($this->TaskSqlArray, $sql);
- }
- }
- }
- private function TaskSQlToRedis()
- {
- if (empty($this->TaskSqlArray)) {
- return;
- }
- $this->TaskSqlArrayCopy = $this->TaskSqlArray;
- $this->TaskSqlArray = [];
- $this->sqltoRedisqueue($this->TaskSqlArrayCopy);
- $this->TaskSqlArrayCopy = [];
- }
- private function sqltoRedisqueue($cmdArray)
- {
- $redisconfig = $this->redisonfig;
- go(function () use ($cmdArray, $redisconfig) {
- $redis = new Swoole\Coroutine\Redis();
- $redis->setOptions(['compatibility_mode' => true]);
- $redis->connect($redisconfig['host'], $redisconfig['port']);
- if (is_array($cmdArray)) {
- $redis->multi();
- foreach ($cmdArray as $cmd) {
- $redis->lpush(self::SQLKEY, $cmd);
- }
- $redis->exec();
- } else {
- $redis->lpush(self::SQLKEY, $cmdArray);
- }
- });
- }
- //sql批量写入数据库
- private function BatchSqlRedisToDB()
- {
- $redisconfig = $this->redisonfig;
- go(function () use ($redisconfig) {
- $redis = new Swoole\Coroutine\Redis();
- $redis->connect($redisconfig['host'], $redisconfig['port']);
- $batchsql = [];
- $max = 1000;
- for ($i = 0; $i < $max; $i++) {
- $now = $redis->rpop(self::SQLKEY);
- if (empty($now)) {
- break;
- } else {
- $batchsql[] = str_replace(";", ";", $now);
- }
- }
- if (!empty($batchsql)) {
- $pdo = DB::getPdo();
- $sqlstr = implode(";", $batchsql);
- $pdo->exec($sqlstr);
- }
- return;
- });
- }
- public function onFinish($serv, int $task_id, $data)
- {
- }
- private function InitDb()
- {
- $over_time = 60 * 5;
- $now = microtime(true);
- if (!$GLOBALS['modeltime']) {
- $GLOBALS['modeltime'] = $now;
- $GLOBALS['model'] = $this->httpserver->worker_id;
- ModelBase::init();
- return;
- }
- if (($now - $GLOBALS['modeltime']) > $over_time) {
- $GLOBALS['modeltime'] = $now;
- $GLOBALS['model'] = $this->httpserver->worker_id;
- ModelBase::close();
- ModelBase::init();
- return;
- }
- }
- public function start()
- {
- $this->httpserver->start();
- }
- }
|