RefreshBookShelf.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. <?php
  2. namespace app\admin\command;
  3. use app\common\constants\Common;
  4. use app\common\library\Redis;
  5. use think\Config;
  6. use think\console\Command;
  7. use think\console\Input;
  8. use think\console\input\Argument;
  9. use think\console\Output;
  10. use think\Db;
  11. use think\Log;
  12. use think\Request;
  13. class RefreshBookShelf extends Command
  14. {
  15. private $dbConnects = [];
  16. private $_cacheBookIds = [];
  17. private $_cacheChapterIds = [];
  18. private $insertShelfData = [];
  19. private $_bookAutoShelfChapterNum = 0;
  20. private $recommendBookIds = [];
  21. private $getChapterIdsCount = 0;
  22. private $insertShelfCount = 0;
  23. private $getUserBookShelfListCount = 0;
  24. protected function configure()
  25. {
  26. $this->setName('RefreshBookShelf')
  27. ->addArgument('startDbNum', Argument::REQUIRED, "第几个数据库开始")
  28. ->addArgument('endDbNum', Argument::REQUIRED, "第几个数据库结束")
  29. ->setDescription('刷新用户书架,用户阅读超过第十章的书籍加入书架');
  30. }
  31. protected function execute(Input $input, Output $output)
  32. {
  33. $beginTime = time();
  34. Request::instance()->module('admin');
  35. $startDbNum = $input->getArgument('startDbNum');
  36. $endDbNum = $input->getArgument('endDbNum');
  37. $output->writeln('开始数据库' . $startDbNum);
  38. $output->writeln('结束数据库' . $endDbNum);
  39. if ($startDbNum > 511 || $endDbNum > 511) {
  40. $output->writeln('参数错误,数据库开始序号和结束序号不能大于511');
  41. die();
  42. }
  43. $model = model('BookshelfRecommand');
  44. $this->recommendBookIds = $model->where('sex', 1)->where('status',
  45. Common::STATUS_NORMAL)->limit(6)->column('book_id');
  46. $this->_bookAutoShelfChapterNum = 8;
  47. Log::info("开始刷书架,开始时间:" . date("Y-m-d H:i:s", time()));
  48. for ($idx = $startDbNum; $idx <= $endDbNum; $idx++) {
  49. try {
  50. $output->writeln($idx);
  51. Log::info("***************************************************************************");
  52. $db = $this->dbConnect($idx, 'shard');
  53. $userRecentlyReadId = 0;
  54. while (true) {
  55. Log::info(sprintf('dbNo:%s,begin_id:%s', $idx, $userRecentlyReadId));
  56. $sql = <<<SQL
  57. select id, book_id, user_id, chapter_id from user_recently_read where flag = 1 and id>$userRecentlyReadId limit 10000;
  58. SQL;
  59. $result = $db->query($sql);
  60. if ($result) {
  61. foreach ($result as $item) {
  62. $autoShelf = $this->checkChapterIdAutoShelf($item['book_id'], $item['chapter_id']);
  63. if ($autoShelf) {
  64. $this->preAutoBookShelf($item['user_id'], $item['book_id'], $item['chapter_id']);
  65. }
  66. }
  67. $lastItem = end($result);
  68. $userRecentlyReadId = $lastItem['id'];
  69. $this->autoBookSelf(false);
  70. Log::info(sprintf('dbNo:%s,last_id:%s', $idx, $userRecentlyReadId));
  71. $this->cleanCount();
  72. } else {
  73. $this->autoBookSelf(true);
  74. Log::info(sprintf('finish_dbNo:%s,last_id:%s', $idx, $userRecentlyReadId));
  75. $this->cleanCount();
  76. break;
  77. }
  78. sleep(0.05);
  79. }
  80. $this->closeDbConnect();
  81. } catch (\Exception $e) {
  82. Log::error($e->getMessage() . $e->getTraceAsString());
  83. Log::error("数据库" . $db->getConfig('database') . "中的信息,出错了,需要重新执行");
  84. }
  85. }
  86. $endTime = time();
  87. $usedTime = $endTime - $beginTime;
  88. Log::info("刷书架完成,结束时间:" . date("Y-m-d H:i:s", time()) . " 耗时:" . $usedTime . 's');
  89. }
  90. /**
  91. * 获取数据库连接
  92. * @param $param 编号
  93. * @param string $deploy 业务
  94. * @return \think\db\Connection
  95. * @throws \think\Exception
  96. */
  97. private function dbConnect($param, $deploy)
  98. {
  99. $db_config = $this->get_db_deploy($param, $deploy);
  100. if (empty($this->dbConnects[$db_config['database']])) {
  101. Log::info(sprintf('打开数据库连接,database:%s', $db_config['database']));
  102. $this->dbConnects[$db_config['database']] = Db::connect($db_config);
  103. }
  104. return $this->dbConnects[$db_config['database']];
  105. }
  106. /**
  107. * 关闭数据库连接
  108. */
  109. private function closeDbConnect()
  110. {
  111. foreach ($this->dbConnects as $database => $dbConnect) {
  112. Log::info(sprintf('关闭数据库连接,database:%s', $database));
  113. $dbConnect->close();
  114. }
  115. $this->dbConnects = [];
  116. }
  117. /**
  118. * 获取db分库的配置参数
  119. *
  120. * @param string|int $param 取模值
  121. * @param string $deploy 分库前缀
  122. * @return array
  123. */
  124. function get_db_deploy($param, $deploy = 'shard')
  125. {
  126. $db = Config::get('db');
  127. $mod = $param % $db[$deploy . '_num'];
  128. $mod = abs($mod);
  129. $list = explode(';', $db[$deploy . '_list']);
  130. foreach ($list as $item) {
  131. $con = explode(':', $item); // 0=0-191库编号 1=192.168.1.149主IP 2=3306主端口 3=192.168.1.150从IP 4=3306从端口
  132. if (count($con) >= 3) {
  133. $c = explode('-', $con[0]); //库编号 0开始 1结束
  134. if (count($c) >= 2) {
  135. if ($c[0] <= $mod && $mod <= $c[1]) {
  136. $database = Config::get('database');
  137. if ($database['deploy'] == 1 && count($con) >= 5) { //开启主从 & 带主从配置
  138. $database['hostname'] = $con[1] . ',' . $con[3]; //192.168.1.149,192.168.1.150
  139. $database['hostport'] = $con[2] . ',' . $con[4]; //3306,3306
  140. } else { //只有主库
  141. $database['hostname'] = $con[1];
  142. $database['hostport'] = $con[2];
  143. }
  144. $database['database'] = str_replace('$mod', $mod, $db[$deploy . '_database']);
  145. return $database;
  146. }
  147. }
  148. }
  149. }
  150. Log::error("分库获取失败!");
  151. return [];
  152. }
  153. /**
  154. * 检查当前章节是否符合自动加入书架的条件
  155. * @param $bookId 书籍id
  156. * @param $chapterId 章节id
  157. * @return bool
  158. */
  159. private function checkChapterIdAutoShelf($bookId, $chapterId)
  160. {
  161. $result = false;
  162. if (in_array($bookId, $this->_cacheBookIds, true)) {
  163. if (!in_array($chapterId, $this->_cacheChapterIds, true)) {
  164. Log::info("putIn,bId:$bookId,cId:$chapterId");
  165. $result = true;
  166. }
  167. } else {
  168. $chapterIds = $this->getChapterIds($bookId);
  169. $this->_cacheBookIds[] = $bookId;
  170. $this->_cacheChapterIds = array_merge($this->_cacheChapterIds, $chapterIds);
  171. if (!in_array($chapterId, $chapterIds, true)) {
  172. Log::info("doNothing1,bId:$bookId,cId:$chapterId");
  173. $result = true;
  174. }
  175. }
  176. if (!$result) {
  177. Log::info("doNothing2,bId:$bookId,cId:$chapterId");
  178. }
  179. if (count($this->_cacheBookIds) > 10000 || count($this->_cacheChapterIds) > 30000) {
  180. $this->_cacheBookIds = null;
  181. $this->_cacheChapterIds = null;
  182. Log::info('cl_cch');
  183. }
  184. return $result;
  185. }
  186. /**
  187. * 获取书籍章节id列表
  188. * @param $bookId
  189. * @return array
  190. */
  191. private function getChapterIds($bookId)
  192. {
  193. $result = [];
  194. if (Config::get('redis.change') == 1) {
  195. $code = $this->getCode('A04' . $bookId);
  196. $redis = Redis::instanceBookChange($code);
  197. $list = $redis->zRange('A04' . $bookId, 0, $this->_bookAutoShelfChapterNum);
  198. } else {
  199. $redis = Redis::instanceBook();
  200. $list = $redis->lRange("basedata_chapter_owchcp_{$bookId}", 0, $this->_bookAutoShelfChapterNum);
  201. }
  202. foreach ($list as $key => $value) {
  203. if (Config::get('redis.change') == 1) {
  204. $json = json_decode($value, true);
  205. } else {
  206. $json = json_decode(gzdecode($value), true);
  207. }
  208. $chapterId = $json[4] ?? $json['chapterId'];
  209. $result[] = intval($chapterId);
  210. }
  211. $this->getChapterIdsCount++;
  212. return $result;
  213. }
  214. private function getCode($val)
  215. {
  216. $bKey = md5($val, true);
  217. $rv = (ord($bKey[3]) & 0xFF) << 24
  218. | (ord($bKey[2]) & 0xFF) << 16
  219. | (ord($bKey[1]) & 0xFF) << 8
  220. | ord($bKey[0]) & 0xFF;
  221. return $rv & 0xffffffff;
  222. }
  223. private function preAutoBookShelf($userId, $bookId, $chapterId)
  224. {
  225. $this->insertShelfData[] = [
  226. 'user_id' => $userId,
  227. 'book_id' => $bookId,
  228. 'chapter_id' => $chapterId,
  229. ];
  230. }
  231. /**
  232. * 将缓存的书架信息插入数据库
  233. * @param bool $forceInsert 强制将缓存的数据插入数据库
  234. * @throws \think\Exception
  235. * @throws \think\exception\PDOException
  236. */
  237. private function autoBookSelf($forceInsert = false)
  238. {
  239. $time = time();
  240. $sql = <<<SQL
  241. insert into book_shelf (user_id, book_id, insert_type, chapter_id, idx, createtime, updatetime) values
  242. SQL;
  243. $count = count($this->insertShelfData);//总条数
  244. if ($count > 100000 || $forceInsert) {
  245. $page = 0;
  246. $pageSize = 10000;
  247. while (true) {
  248. $start = $page * $pageSize;
  249. $_insertShelfDataPart = array_slice($this->insertShelfData, $start, $pageSize);
  250. if (empty($_insertShelfDataPart)) {
  251. $this->insertShelfData = null;
  252. break;
  253. } else {
  254. $insertGroupList = [];
  255. $userIds = array_column($_insertShelfDataPart, 'user_id');
  256. $userIdBookIdRels = $this->getUserBookShelfList($userIds);
  257. $begTime = time();
  258. foreach ($_insertShelfDataPart as $item) {
  259. $_userIdBookId = sprintf('%s_%s', $item['user_id'], $item['book_id']);
  260. if (in_array($_userIdBookId, $userIdBookIdRels, true)) {
  261. Log::info(sprintf('doNothing3,uId:%s,bId:%s', $item['user_id'],
  262. $item['book_id']));
  263. continue;
  264. }
  265. $config = $this->get_db_deploy($item['user_id'], 'shelf');
  266. $insertGroupList[$config['database']][] = <<<SQL
  267. ({$item['user_id']}, {$item['book_id']}, 2, {$item['chapter_id']}, 0, {$time}, {$time})
  268. SQL;
  269. }
  270. $subTime = time() - $begTime;
  271. Log::info('charge_in_time:' . $subTime . 's');
  272. foreach ($insertGroupList as $dbName => $values) {
  273. $aas = explode('_', $dbName);
  274. if (count($aas) > 0) {
  275. $param = end($aas);
  276. $insValStr = implode(',', $values);
  277. $sqlInsertBat = $sql . $insValStr;
  278. $db = $this->dbConnect($param, 'shelf');
  279. $db->execute($sqlInsertBat);
  280. $this->insertShelfCount++;
  281. }
  282. }
  283. }
  284. sleep(0.05);
  285. $page++;
  286. }
  287. $this->insertShelfData = [];
  288. }
  289. }
  290. /**
  291. * 获取已经存在的用户书架关系
  292. * @param $userIds
  293. * @return array
  294. * @throws \think\Exception
  295. * @throws \think\exception\PDOException
  296. */
  297. private function getUserBookShelfList($userIds)
  298. {
  299. $begTime = time();
  300. $result = [];
  301. $userGroupList = [];
  302. foreach ($userIds as $userId) {
  303. $config = $this->get_db_deploy($userId, 'shelf');
  304. $userGroupList[$config['database']][] = $userId;
  305. }
  306. foreach ($userGroupList as $dbName => $_userIds) {
  307. $_userId = end($_userIds);
  308. $db = $this->dbConnect($_userId, 'shelf');
  309. $sql = <<<SQL
  310. select user_id, book_id from book_shelf where user_id in (%s)
  311. SQL;
  312. $strUserIds = implode(',', $_userIds);
  313. $sql = sprintf($sql, $strUserIds);
  314. $bookResult = $db->query($sql);
  315. $this->getUserBookShelfListCount++;
  316. foreach ($bookResult as $item) {
  317. $result[] = sprintf('%s_%s', $item['user_id'], $item['book_id']);
  318. }
  319. }
  320. $subTime = time() - $begTime;
  321. Log::info('getUserBookShelfList:' . $subTime);
  322. return $result;
  323. }
  324. private function cleanCount()
  325. {
  326. Log::info(sprintf('getChapterIdsCount:%s,insertShelfCount:%s,getUserBookShelfListCount:%s',
  327. $this->getChapterIdsCount, $this->insertShelfCount, $this->getUserBookShelfListCount));
  328. }
  329. }