HttpServerSettelement.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2019/6/26
  6. * Time: 12:03
  7. */
  8. namespace datainf\logic;
  9. use App\Lib\ModelBase;
  10. use App\Http\Response\Response;
  11. use App\Logic\WinfailLogic;
  12. use datainf\lib\GlobConfigs;
  13. use Illuminate\Database\Capsule\Manager as DB;
  14. use swoole;
  15. use App\Logic\SettelementLogic;
  16. class HttpServerSettelement
  17. {
  18. private $httpserver;
  19. private $config;
  20. private $dbpooleconfig = [];
  21. private $redisonfig = [];
  22. const SQLKEY = 'ALLSQLKEY';
  23. private $TaskSqlArray = [];
  24. private $TaskSqlArrayCopy = [];
  25. use SettelementLogic;
  26. public function __construct($config)
  27. {
  28. $this->httpserver = new \swoole\http\server($config['host'], $config['port']);
  29. $this->httpserver->set($config['sets']);
  30. $this->config = $config;
  31. $this->dbpooleconfig = GlobConfigs::getKey('pgsqlpoole');
  32. $this->redisonfig = GlobConfigs::getKey('redis');
  33. $taskWorkingNum = new \swoole\Atomic();
  34. $this->httpserver->taskWorkingNum = $taskWorkingNum;
  35. $this->httpserver->on('request', array($this, 'OnRequest'));
  36. $this->httpserver->on('WorkerStart', array($this, 'onWorkerStart'));
  37. $this->httpserver->on('task', array($this, 'onTask'));
  38. $this->httpserver->on('finish', array($this, 'onFinish'));
  39. }
  40. public function onWorkerStart($serv, $worker_id)
  41. {
  42. $name = $serv->taskworker ? 'Task_' : 'Worker_';
  43. $name = 'Settelement_' . $name . ($serv->worker_id < 10 ? '0' . $serv->worker_id : $serv->worker_id);
  44. swoole_set_process_name($name);
  45. $GLOBALS['model'] = '';
  46. $GLOBALS['modeltime'] = 0;
  47. if (!$serv->taskworker) {
  48. $this->InitDb();
  49. } else {
  50. $obj = $this;
  51. Swoole\Timer::tick(1000, function ($id) use ($obj) {
  52. $obj->TaskSQlToRedis();
  53. });
  54. }
  55. if ($worker_id == 0) {
  56. $obj = $this;
  57. Swoole\Timer::tick(5000, function ($id) use ($obj) {
  58. $obj->BatchSqlRedisToDB();
  59. });
  60. }
  61. }
  62. public function OnRequest($request, $response)
  63. {
  64. $response->header('Content-Type', 'text/html; charset=utf-8');
  65. $response->header('Server', 'DataInfaceServer');
  66. $paras = array_merge(['request_time' => date("H:i:s")], !empty($request->get) ? $request->get : [], !empty($request->post) ? $request->post : []);
  67. $request_uri = substr($request->server['request_uri'], 1);
  68. $urls = ['WinFail', 'Settelement'];
  69. if (!in_array($request_uri, $urls)) {
  70. $data = Response::generate('', 0, '', '无效的url');
  71. $response->end($data);
  72. return;
  73. }
  74. if ($this->httpserver->taskWorkingNum->get() > 0) {
  75. $data = Response::generate('', 9, '', '还有未完成任务请稍等...');
  76. $response->end($data);
  77. return;
  78. }
  79. $check_token = true;
  80. if ($check_token) {
  81. $token = isset($paras['token']) ? $paras['token'] : '';
  82. if (empty($token) || empty($this->Tokencheck($token))) {
  83. $data = Response::generate('', 6, '', '安全验证失败!');
  84. $response->end($data);
  85. return;
  86. }
  87. }
  88. if ($request_uri == 'WinFail') {
  89. return $this->doWinFailse($request, $response, $paras);
  90. }
  91. if ($request_uri == 'Settelement') {
  92. return $this->doSettelement($request, $response, $paras);
  93. }
  94. return;
  95. }
  96. public function onTask($serv, $task)
  97. {
  98. $this->httpserver->taskWorkingNum->add();
  99. if ($task['type'] == 'doWinFailse') {
  100. $this->Task_winfalse($serv, $task);
  101. }
  102. if ($task['type'] == 'Settelement') {
  103. $this->Task_Settelement($serv, $task);
  104. }
  105. $this->httpserver->taskWorkingNum->sub();
  106. }
  107. private function Tokencheck($token)
  108. {
  109. $tokenvel = DB::table('system_user')->where(['token' => $token])->first();
  110. return $tokenvel;
  111. }
  112. //胜负计算
  113. private function doWinFailse($request, $response, $paras)
  114. {
  115. $logic_obj = new WinfailLogic();
  116. $notice = isset($paras['noticeid']) ? $paras['noticeid'] : 0;
  117. $id = intval($notice);
  118. try {
  119. $noticeModel = $logic_obj->getNoticeDate($id);
  120. $result = $logic_obj->getCompResult($noticeModel->game_code, $noticeModel->match_id);
  121. $moneySimples = $logic_obj->getSimplexData($noticeModel->game_code, $noticeModel->match_id);
  122. $matchs_1 = $logic_obj->getMatchRecords($noticeModel->game_code, $noticeModel->match_id, 1);
  123. $matchs_2 = $logic_obj->getMatchRecords($noticeModel->game_code, $noticeModel->match_id, 2);
  124. $match_firstModel = isset($matchs_1['0']) ? $matchs_1['0'] : (isset($matchs_2['0']) ? $matchs_2['0'] : false);
  125. if (!$match_firstModel) {
  126. throw new \Exception('无数据异常-1!');
  127. return true;
  128. }
  129. $gjModel = $logic_obj->getGjDatas($match_firstModel);
  130. if (count($matchs_1) > 0 && count($moneySimples) <= 0) {
  131. throw new \Exception('数据异常-2!');
  132. }
  133. if (strtolower($match_firstModel->p_code) == 'gj') {
  134. if (empty($gjModel)) {
  135. throw new \Exception("没有冠军数据数据--match_id" . $noticeModel->match_id);
  136. }
  137. $result = [$gjModel];
  138. }
  139. if (!empty($matchs_1)) {
  140. while (true) {
  141. if ($this->httpserver->taskWorkingNum->get() > intval($this->config['sets']['task_worker_num'])) {
  142. co::sleep(50);
  143. } else {
  144. $now = array_shift($matchs_1);
  145. if (empty($now)) {
  146. break;
  147. }
  148. $paras = ['type' => 'doWinFailse', 'stype' => 1, 'matchModel' => $now, 'result' => $result, 'moneySimple' => $moneySimples[$now->batch_id][$now->match_id]];
  149. $this->onTask($this->httpserver, $paras);
  150. }
  151. }
  152. }
  153. if (!empty($matchs_2)) {
  154. while (true) {
  155. if ($this->httpserver->taskWorkingNum->get() > intval($this->config['sets']['task_worker_num'])) {
  156. co::sleep(50);
  157. } else {
  158. $now = array_shift($matchs_2);
  159. if (empty($now)) {
  160. break;
  161. }
  162. $paras = ['type' => 'doWinFailse', 'stype' => 1, 'matchModel' => $now, 'result' => $result, 'moneySimple' => $moneySimples[$now->batch_id][$now->match_id]];
  163. $this->onTask($this->httpserver, $paras);
  164. }
  165. }
  166. }
  167. unset($logic_obj, $noticeModel, $AdapterObj, $result, $moneySimples, $matchs_1, $matchs_2, $RefClass);
  168. $this->httpserver->taskWorkingNum->add();
  169. $this->sqltoRedisqueue($this->TaskSqlArray);
  170. $this->httpserver->taskWorkingNum->sub();
  171. $data = Response::generate('', 1, ['cost' => (microtime(true) - $request->server['request_time_float'])], 'succes ');
  172. $response->end($data);
  173. return;
  174. } catch (\Exception $e) {
  175. unset($logic_obj);
  176. $data = Response::generate('', 10, '', $e->getMessage() . '--' . $e->getFile() . '--' . $e->getLine());
  177. $response->end($data);
  178. return;
  179. }
  180. return;
  181. }
  182. /////
  183. private function Task_winfalse($serv, $task)
  184. {
  185. try {
  186. $moneyBuy = $task['moneySimple'];
  187. $matchModel = $task['matchModel'];
  188. $logic = WinfailLogic::getInstance();
  189. $AdapterObj = $logic->getAdapterObj($matchModel->game_code);
  190. $RefClass = new \ReflectionClass($AdapterObj);
  191. //如果手动更改了结果,就用更改后的结果,否则用默认的结果
  192. if ($matchModel->bet_type == 1 && $moneyBuy['result_flag'] == 1) {
  193. $now_result = [json_decode($moneyBuy['single_result'])];
  194. } else {
  195. foreach ($task['result'] as $key => $val) {
  196. $now_result[] = $val;
  197. }
  198. }
  199. $fun1 = $matchModel->odds_code;
  200. $fun2 = $matchModel->p_code;
  201. $winorfalsedef = ['result' => 2, 'matchResult' => 'noRuleOrError'];
  202. try {
  203. if ($RefClass->hasMethod($fun1)) {
  204. $winorfalse = $AdapterObj->$fun1($matchModel, $now_result, []);
  205. } elseif ($RefClass->hasMethod($fun2)) {
  206. $winorfalse = $AdapterObj->$fun2($matchModel, $now_result, []);
  207. }
  208. } catch (\Exception $e) {
  209. }
  210. if (!isset($winorfalse['result']) || !isset($winorfalse['matchResult']) || !in_array($winorfalse['result'], [-1, 1, 2, 3, 4])) {
  211. $winorfalse = $winorfalsedef;
  212. }
  213. $sql_1 = $this->makesql_up_buymatch_winorfalse($matchModel->id, $winorfalse['result'], date("Y-m-d H:i:s"), $winorfalse['matchResult']);
  214. $gs_val = ($winorfalse['result'] == 1) ? 1 : ($winorfalse['result'] == -1 ? 2 : 3);
  215. if ($matchModel->bet_type == 1) {
  216. $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' ";
  217. } else {
  218. $sql_2 = "update money_buy_str set wait_match_num=wait_match_num-1 where batch_id='$matchModel->batch_id' ";
  219. }
  220. $this->PushSqlToArray([$sql_1, $sql_2]);
  221. } catch (\Exception $e) {
  222. echo $e->getMessage() . '--' . $e->getFile() . '--' . $e->getLine() . "\n";
  223. }
  224. return true;
  225. }
  226. //生成更新sql;
  227. private function makesql_up_buymatch_winorfalse($id, $result, $utime, $matchResult = '')
  228. {
  229. $matchResult = str_replace(";", ";", $matchResult);
  230. $sql = "update money_buy_match set result=$result, utime='$utime',matchResult='$matchResult' where id=$id ";
  231. return $sql;
  232. }
  233. /*
  234. private function DbpooleClient($sqlArray = [])
  235. {
  236. go(function () use ($sqlArray) {
  237. $client = new \swoole_client(SWOOLE_SOCK_TCP);
  238. if (!$client->connect('127.0.0.1', $this->dbpooleconfig['poole_port'], 1)) {
  239. return false;
  240. }
  241. foreach ($sqlArray as $val) {
  242. $cmds[] = $val;
  243. }
  244. $this->sqltoRedisqueue($cmds);
  245. $client->close();
  246. });
  247. }
  248. */
  249. private function PushSqlToArray($cmdArray)
  250. {
  251. if (is_string($cmdArray)) {
  252. array_push($this->TaskSqlArray, $cmdArray);
  253. } else {
  254. foreach ($cmdArray as $sql) {
  255. array_push($this->TaskSqlArray, $sql);
  256. }
  257. }
  258. }
  259. private function TaskSQlToRedis()
  260. {
  261. if (empty($this->TaskSqlArray)) {
  262. return;
  263. }
  264. $this->TaskSqlArrayCopy = $this->TaskSqlArray;
  265. $this->TaskSqlArray = [];
  266. $this->sqltoRedisqueue($this->TaskSqlArrayCopy);
  267. $this->TaskSqlArrayCopy = [];
  268. }
  269. private function sqltoRedisqueue($cmdArray)
  270. {
  271. $redisconfig = $this->redisonfig;
  272. go(function () use ($cmdArray, $redisconfig) {
  273. $redis = new Swoole\Coroutine\Redis();
  274. $redis->setOptions(['compatibility_mode' => true]);
  275. $redis->connect($redisconfig['host'], $redisconfig['port']);
  276. if (is_array($cmdArray)) {
  277. $redis->multi();
  278. foreach ($cmdArray as $cmd) {
  279. $redis->lpush(self::SQLKEY, $cmd);
  280. }
  281. $redis->exec();
  282. } else {
  283. $redis->lpush(self::SQLKEY, $cmdArray);
  284. }
  285. });
  286. }
  287. //sql批量写入数据库
  288. private function BatchSqlRedisToDB()
  289. {
  290. $redisconfig = $this->redisonfig;
  291. go(function () use ($redisconfig) {
  292. $redis = new Swoole\Coroutine\Redis();
  293. $redis->connect($redisconfig['host'], $redisconfig['port']);
  294. $batchsql = [];
  295. $max = 5000;
  296. for ($i = 0; $i < $max; $i++) {
  297. $now = $redis->rpop(self::SQLKEY);
  298. if (empty($now)) {
  299. break;
  300. } else {
  301. $batchsql[] = str_replace(";", ";", $now);
  302. }
  303. }
  304. if (!empty($batchsql)) {
  305. $pdo = DB::getPdo();
  306. $sqlstr = implode(";", $batchsql);
  307. $pdo->exec($sqlstr);
  308. }
  309. return;
  310. });
  311. }
  312. public function onFinish($serv, int $task_id, $data)
  313. {
  314. }
  315. private function InitDb()
  316. {
  317. $over_time = 60 * 5;
  318. $now = microtime(true);
  319. if (!$GLOBALS['modeltime']) {
  320. $GLOBALS['modeltime'] = $now;
  321. $GLOBALS['model'] = $this->httpserver->worker_id;
  322. ModelBase::init();
  323. return;
  324. }
  325. if (($now - $GLOBALS['modeltime']) > $over_time) {
  326. $GLOBALS['modeltime'] = $now;
  327. $GLOBALS['model'] = $this->httpserver->worker_id;
  328. ModelBase::close();
  329. ModelBase::init();
  330. return;
  331. }
  332. }
  333. public function start()
  334. {
  335. $this->httpserver->start();
  336. }
  337. }