RefreshRecommendBookShelf.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. namespace app\admin\command;
  3. use app\common\constants\Common;
  4. use app\common\library\Redis;
  5. use app\main\helper\ArrayHelper;
  6. use think\Config;
  7. use think\console\Command;
  8. use think\console\Input;
  9. use think\console\input\Option;
  10. use think\console\Output;
  11. use think\Db;
  12. use think\Log;
  13. use think\Request;
  14. class RefreshRecommendBookShelf extends Command
  15. {
  16. private $recommendBookIds = [];
  17. private $dbConnects = [];
  18. private $insertShelfData = [];
  19. protected function configure()
  20. {
  21. $this->setName('RefreshRecommendBookShelf')
  22. ->addOption('startDbNum', 's', Option::VALUE_REQUIRED, '第几个数据库开始')
  23. ->addOption('endDbNum', 'e', Option::VALUE_REQUIRED, '第几个数据库结束')
  24. ->addOption('channelIds', 'c', Option::VALUE_REQUIRED, '渠道商id列表,逗号分隔')
  25. ->setDescription('将书库推荐书插入用户书架');
  26. }
  27. protected function execute(Input $input, Output $output)
  28. {
  29. $beginTime = time();
  30. Request::instance()->module('admin'); //cli模式下无法获取到当前的项目模块,手动指定一下
  31. $model = model('BookshelfRecommand');
  32. $this->recommendBookIds[1] = $model->where('sex', 1)->where('status',
  33. Common::STATUS_NORMAL)->order('id')->limit(6)->column('book_id');
  34. $this->recommendBookIds[2] = $model->where('sex', 2)->where('status',
  35. Common::STATUS_NORMAL)->order('id')->limit(6)->column('book_id');
  36. $startDbNum = $input->getOption('startDbNum');
  37. $endDbNum = $input->getOption('endDbNum');
  38. $strChannelIds = $input->getOption('channelIds');
  39. $output->writeln('开始数据库' . $startDbNum);
  40. $output->writeln('结束数据库' . $endDbNum);
  41. $output->writeln('渠道商id:' . $strChannelIds);
  42. if ($startDbNum > 511 || $endDbNum > 511) {
  43. $output->writeln('参数错误,数据库开始序号和结束序号不能大于511');
  44. die();
  45. }
  46. if (empty($strChannelIds)) {
  47. $output->writeln('渠道商id不能为空');
  48. die();
  49. }
  50. $channelIds = explode(',', $strChannelIds);
  51. foreach ($channelIds as $channelId) {
  52. if (!is_numeric($channelId)) {
  53. $output->writeln("$channelId 不是整数");
  54. } else {
  55. $output->writeln($channelId);
  56. }
  57. }
  58. for ($idx = $startDbNum; $idx <= $endDbNum; $idx++) {
  59. try {
  60. $output->writeln($idx);
  61. Log::info("***************************************************************************");
  62. $beginUserId = 0;
  63. while (true) {
  64. $result = $this->getUserInfo($idx, $beginUserId, $strChannelIds);
  65. if ($result) {
  66. $userIds = array_column($result, 'id');
  67. $userIdsHasShelf = $this->getBookShelfUserIds($idx, $userIds);
  68. $userIds = array_diff($userIds, $userIdsHasShelf);
  69. $tmpRes = [];
  70. $bookShelfKeys = [];
  71. foreach ($userIds as $userId) {
  72. $tmpRes[] = ArrayHelper::array_column_search($result, 'id', $userId);
  73. $bookShelfKeys[] = "SBIK:$userId";
  74. }
  75. $redis = Redis::instance();
  76. $redis->del(...$bookShelfKeys);
  77. foreach ($tmpRes as $item) {
  78. $this->preAutoBookShelf($item['id'], $item['sex']);
  79. }
  80. $lastItem = end($result);
  81. $beginUserId = $lastItem['id'];
  82. $this->autoBookSelf(false);
  83. Log::info(sprintf('dbNo:%s,last_id:%s', $idx, $beginUserId));
  84. sleep(0.05);
  85. } else {
  86. $this->autoBookSelf(true);
  87. Log::info(sprintf('finish_dbNo:%s,last_id:%s', $idx, $beginUserId));
  88. break;
  89. }
  90. }
  91. $this->closeDbConnect();
  92. } catch (\Exception $e) {
  93. Log::error($e->getMessage());
  94. }
  95. }
  96. $endTime = time();
  97. $usedTime = $endTime - $beginTime;
  98. Log::info("书库推荐书插入用户书架完成,结束时间:" . date("Y-m-d H:i:s", $endTime) . " 耗时:" . $usedTime . 's');
  99. }
  100. /**
  101. * 获取用户信息
  102. * @param $dbIdx 数据库索引
  103. * @param $beginUserId 起始用户id
  104. * @param $strChannelIds 渠道商id列表
  105. * @param int $limit
  106. * @return mixed
  107. * @throws \think\Exception
  108. * @throws \think\exception\PDOException
  109. */
  110. private function getUserInfo($dbIdx, $beginUserId, $strChannelIds, $limit = 1000)
  111. {
  112. $db = $this->dbConnect($dbIdx, 'user');
  113. Log::info(sprintf('dbNo:%s,begin_id:%s', $dbIdx, $beginUserId));
  114. $sql = <<<SQL
  115. select id, sex from user where id > $beginUserId and channel_id in($strChannelIds) limit $limit;
  116. SQL;
  117. $result = $db->query($sql);
  118. return $result;
  119. }
  120. /**
  121. * 获取有书架信息的用户id
  122. * @param $dbIdx 数据库索引
  123. * @param array $userIds 用户id列表
  124. * @return array|mixed
  125. * @throws \think\Exception
  126. * @throws \think\exception\PDOException
  127. */
  128. private function getBookShelfUserIds($dbIdx, array $userIds)
  129. {
  130. if (empty($userIds)) {
  131. return [];
  132. }
  133. $strUserIds = implode(',', $userIds);
  134. $db = $this->dbConnect($dbIdx, 'shelf');
  135. $sql = <<<SQL
  136. select distinct user_id from book_shelf where user_id in($strUserIds);
  137. SQL;
  138. $result = $db->query($sql);
  139. $resUserIds = array_column($result, 'user_id');
  140. return $resUserIds;
  141. }
  142. /**
  143. * 获取数据库连接
  144. * @param $param 编号
  145. * @param $deploy 业务
  146. * @return \think\db\Connection
  147. * @throws \think\Exception
  148. */
  149. private function dbConnect($param, $deploy)
  150. {
  151. $db_config = $this->get_db_deploy($param, $deploy);
  152. if (empty($this->dbConnects[$db_config['database']])) {
  153. $this->dbConnects[$db_config['database']] = Db::connect($db_config);
  154. }
  155. return $this->dbConnects[$db_config['database']];
  156. }
  157. /**
  158. * 关闭数据库连接
  159. */
  160. private function closeDbConnect()
  161. {
  162. foreach ($this->dbConnects as $database => $dbConnect) {
  163. Log::info(sprintf('关闭数据库连接,database:%s', $database));
  164. $dbConnect->close();
  165. }
  166. $this->dbConnects = [];
  167. }
  168. /**
  169. * 获取db分库的配置参数
  170. *
  171. * @param string|int $param 取模值
  172. * @param string $deploy 分库前缀
  173. * @return array
  174. */
  175. function get_db_deploy($param, $deploy = 'shard')
  176. {
  177. $db = Config::get('db');
  178. $mod = $param % $db[$deploy . '_num'];
  179. $mod = abs($mod);
  180. $list = explode(';', $db[$deploy . '_list']);
  181. foreach ($list as $item) {
  182. $con = explode(':', $item); // 0=0-191库编号 1=192.168.1.149主IP 2=3306主端口 3=192.168.1.150从IP 4=3306从端口
  183. if (count($con) >= 3) {
  184. $c = explode('-', $con[0]); //库编号 0开始 1结束
  185. if (count($c) >= 2) {
  186. if ($c[0] <= $mod && $mod <= $c[1]) {
  187. $database = Config::get('database');
  188. if ($database['deploy'] == 1 && count($con) >= 5) { //开启主从 & 带主从配置
  189. $database['hostname'] = $con[1] . ',' . $con[3]; //192.168.1.149,192.168.1.150
  190. $database['hostport'] = $con[2] . ',' . $con[4]; //3306,3306
  191. } else { //只有主库
  192. $database['hostname'] = $con[1];
  193. $database['hostport'] = $con[2];
  194. }
  195. $database['database'] = str_replace('$mod', $mod, $db[$deploy . '_database']);
  196. return $database;
  197. }
  198. }
  199. }
  200. }
  201. Log::error("分库获取失败!");
  202. return [];
  203. }
  204. /**
  205. * @param $userId
  206. * @param $sex
  207. */
  208. private function preAutoBookShelf($userId, $sex)
  209. {
  210. $sex = $sex == 0 ? 1 : $sex;
  211. $bookIds = $this->recommendBookIds[$sex];
  212. foreach ($bookIds as $bookId) {
  213. $this->insertShelfData[] = [
  214. 'user_id' => $userId,
  215. 'book_id' => $bookId,
  216. ];
  217. }
  218. }
  219. /**
  220. * 将书架书籍插入数据库
  221. * @param bool $forceInsert 是否强制刷入数据库。如果不强制刷入数据库,insertShelfData的数量大于10000会刷入数据库
  222. * @throws \think\Exception
  223. * @throws \think\exception\PDOException
  224. */
  225. private function autoBookSelf($forceInsert = false)
  226. {
  227. $time = time();
  228. $sql = <<<SQL
  229. insert into book_shelf (user_id, book_id, insert_type, createtime, updatetime) values
  230. SQL;
  231. $count = count($this->insertShelfData);//总条数
  232. if ($count == 0) {
  233. return;
  234. }
  235. if ($count > 10000 || $forceInsert) {
  236. $page = 0;
  237. $pageSize = 1000;
  238. while (true) {
  239. $start = $page * $pageSize;//偏移量,当前页-1乘以每页显示条数
  240. $_insertShelfDataPart = array_slice($this->insertShelfData, $start, $pageSize);
  241. if (empty($_insertShelfDataPart)) {
  242. $this->insertShelfData = null;
  243. break;
  244. } else {
  245. $insertValueList = [];
  246. foreach ($_insertShelfDataPart as $item) {
  247. $insertValueList[] = <<<SQL
  248. ({$item['user_id']}, {$item['book_id']}, 1, {$time}, {$time})
  249. SQL;
  250. }
  251. $insValStr = implode(',', $insertValueList);
  252. $sqlInsertBat = $sql . $insValStr;
  253. $db = $this->dbConnect($item['user_id'], 'shelf');
  254. $db->execute($sqlInsertBat);
  255. sleep(0.05);
  256. }
  257. $page++;
  258. }
  259. }
  260. }
  261. }