HttpServerSettelement.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. $id = intval($paras['noticeid']);
  110. try {
  111. $noticeModel = $logic_obj->getNoticeDate($id);
  112. $result = $logic_obj->getCompResult($noticeModel->game_code, $noticeModel->match_id);
  113. $moneySimples = $logic_obj->getSimplexData($noticeModel->game_code, $noticeModel->match_id);
  114. $matchs_1 = $logic_obj->getMatchRecords($noticeModel->game_code, $noticeModel->match_id, 1);
  115. $matchs_2 = $logic_obj->getMatchRecords($noticeModel->game_code, $noticeModel->match_id, 2);
  116. $match_firstModel = isset($matchs_1['0']) ? $matchs_1['0'] : (isset($matchs_2['0']) ? isset($matchs_2['0']) : false);
  117. if (!$match_firstModel) {
  118. return false;
  119. }
  120. $gjModel = $logic_obj->getGjDatas($match_firstModel);
  121. if (strtolower($match_firstModel->p_code) == 'gj') {
  122. if (empty($gjModel)) {
  123. throw new \Exception("没有冠军数据数据--match_id" . $noticeModel->match_id);
  124. }
  125. $result = [$gjModel];
  126. }
  127. if (!empty($matchs_1)) {
  128. while (true) {
  129. if ($this->httpserver->taskWorkingNum->get() > intval($this->config['sets']['task_worker_num'])) {
  130. co::sleep(50);
  131. } else {
  132. $now = array_shift($matchs_1);
  133. if (empty($now)) {
  134. break;
  135. }
  136. $paras = ['type' => 'doWinFailse', 'stype' => 1, 'matchModel' => $now, 'result' => $result, 'moneySimple' => $moneySimples[$now->batch_id][$now->match_id]];
  137. $this->onTask($this->httpserver, $paras);
  138. }
  139. }
  140. }
  141. if (!empty($matchs_2)) {
  142. while (true) {
  143. if ($this->httpserver->taskWorkingNum->get() > intval($this->config['sets']['task_worker_num'])) {
  144. co::sleep(50);
  145. } else {
  146. $now = array_shift($matchs_2);
  147. if (empty($now)) {
  148. break;
  149. }
  150. $paras = ['type' => 'doWinFailse', 'stype' => 1, 'matchModel' => $now, 'result' => $result, 'moneySimple' => $moneySimples[$now->batch_id][$now->match_id]];
  151. $this->onTask($this->httpserver, $paras);
  152. }
  153. }
  154. }
  155. unset($logic_obj, $noticeModel, $AdapterObj, $result, $moneySimples, $matchs_1, $matchs_2, $RefClass);
  156. $data = Response::generate('', 1, ['cost' => (microtime(true) - $request->server['request_time_float'])], 'succes ');
  157. $response->end($data);
  158. return;
  159. } catch (\Exception $e) {
  160. unset($logic_obj);
  161. $data = Response::generate('', 10, '', $e->getMessage() . '--' . $e->getFile() . '--' . $e->getLine());
  162. $response->end($data);
  163. return;
  164. }
  165. return;
  166. }
  167. /////
  168. private function Task_winfalse($serv, $task)
  169. {
  170. try {
  171. $moneyBuy = $task['moneySimple'];
  172. $matchModel = $task['matchModel'];
  173. $logic = WinfailLogic::getInstance();
  174. $AdapterObj = $logic->getAdapterObj($matchModel->game_code);
  175. $RefClass = new \ReflectionClass($AdapterObj);
  176. //如果手动更改了结果,就用更改后的结果,否则用默认的结果
  177. if ($matchModel->bet_type == 1 && $moneyBuy['result_flag'] == 1) {
  178. $now_result = [json_decode($moneyBuy['single_result'])];
  179. } else {
  180. foreach ($task['result'] as $key => $val) {
  181. $now_result[] = $val;
  182. }
  183. }
  184. $fun1 = $matchModel->odds_code;
  185. $fun2 = $matchModel->p_code;
  186. $winorfalsedef = ['result' => 2, 'matchResult' => 'noRuleOrError'];
  187. try {
  188. if ($RefClass->hasMethod($fun1)) {
  189. $winorfalse = $AdapterObj->$fun1($matchModel, $now_result, []);
  190. } elseif ($RefClass->hasMethod($fun2)) {
  191. $winorfalse = $AdapterObj->$fun2($matchModel, $now_result, []);
  192. }
  193. } catch (\Exception $e) {
  194. }
  195. if (!isset($winorfalse['result']) || !isset($winorfalse['matchResult']) || !in_array($winorfalse['result'], [-1, 1, 2, 3, 4])) {
  196. $winorfalse = $winorfalsedef;
  197. }
  198. $sql_1 = $this->makesql_up_buymatch_winorfalse($matchModel->id, $winorfalse['result'], date("Y-m-d H:i:s"), $winorfalse['matchResult']);
  199. $gs_val = ($winorfalse['result'] == 1) ? 1 : ($winorfalse['result'] == -1 ? 2 : 3);
  200. if ($matchModel->bet_type == 1) {
  201. $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' ";
  202. } else {
  203. $sql_2 = "update money_buy_str set wait_match_num=wait_match_num-1 where batch_id='$matchModel->batch_id' ";
  204. }
  205. $this->sqltoRedisqueue([$sql_1, $sql_2]);
  206. } catch (\Exception $e) {
  207. }
  208. return true;
  209. }
  210. //生成更新sql;
  211. private function makesql_up_buymatch_winorfalse($id, $result, $utime, $matchResult = '')
  212. {
  213. $matchResult = str_replace(";", ";", $matchResult);
  214. $sql = "update money_buy_match set result=$result, utime='$utime',matchResult='$matchResult' where id=$id ";
  215. return $sql;
  216. }
  217. /*
  218. private function DbpooleClient($sqlArray = [])
  219. {
  220. go(function () use ($sqlArray) {
  221. $client = new \swoole_client(SWOOLE_SOCK_TCP);
  222. if (!$client->connect('127.0.0.1', $this->dbpooleconfig['poole_port'], 1)) {
  223. return false;
  224. }
  225. foreach ($sqlArray as $val) {
  226. $cmds[] = $val;
  227. }
  228. $this->sqltoRedisqueue($cmds);
  229. $client->close();
  230. });
  231. }
  232. */
  233. private function sqltoRedisqueue($cmdArray)
  234. {
  235. $redisconfig = $this->redisonfig;
  236. go(function () use ($cmdArray, $redisconfig) {
  237. $redis = new Swoole\Coroutine\Redis();
  238. $redis->connect($redisconfig['host'], $redisconfig['port']);
  239. if (is_array($cmdArray)) {
  240. foreach ($cmdArray as $cmd) {
  241. $redis->lpush(self::SQLKEY, $cmd);
  242. }
  243. } else {
  244. $redis->lpush(self::SQLKEY, $cmdArray);
  245. }
  246. });
  247. }
  248. //sql批量写入数据库
  249. private function BatchSqlRedisToDB()
  250. {
  251. $redisconfig = $this->redisonfig;
  252. go(function () use ($redisconfig) {
  253. $redis = new Swoole\Coroutine\Redis();
  254. $redis->connect($redisconfig['host'], $redisconfig['port']);
  255. $batchsql = [];
  256. $max = 3000;
  257. for ($i = 0; $i < $max; $i++) {
  258. $now = $redis->rpop(self::SQLKEY);
  259. if (empty($now)) {
  260. break;
  261. } else {
  262. $batchsql[] = str_replace(";", ";", $now);
  263. }
  264. }
  265. if (!empty($batchsql)) {
  266. $pdo = DB::getPdo();
  267. $sqlstr = implode(";", $batchsql);
  268. $pdo->exec($sqlstr);
  269. }
  270. return;
  271. });
  272. }
  273. public function onFinish($serv, int $task_id, $data)
  274. {
  275. }
  276. private function InitDb()
  277. {
  278. $over_time = 60 * 5;
  279. $now = microtime(true);
  280. if (!$GLOBALS['modeltime']) {
  281. $GLOBALS['modeltime'] = $now;
  282. $GLOBALS['model'] = $this->httpserver->worker_id;
  283. ModelBase::init();
  284. return;
  285. }
  286. if (($now - $GLOBALS['modeltime']) > $over_time) {
  287. $GLOBALS['modeltime'] = $now;
  288. $GLOBALS['model'] = $this->httpserver->worker_id;
  289. ModelBase::close();
  290. ModelBase::init();
  291. return;
  292. }
  293. }
  294. public function start()
  295. {
  296. $this->httpserver->start();
  297. }
  298. }