HttpServerSettelement.php 12 KB

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