cache = $this->getDI()->get('cache'); $this->redis = $this->cache->getRedis(); $this->rebuild(); } protected function rebuild() { $key = $this->getCacheKey(); $commentIds = $this->redis->sRandMember($key, 500); if (!$commentIds) return; $commentRepo = new CommentRepo(); $comments = $commentRepo->findByIds($commentIds); if ($comments->count() == 0) { return; } $counterCache = new CommentCounterCache(); $hour = date('H'); $recount = $this->checkEnableRecount(); foreach ($comments as $comment) { if ($recount && $hour % 3 == 0) { $comment->reply_count = $commentRepo->countReplies($comment->id); $comment->agree_count = $commentRepo->countAgrees($comment->id); $comment->oppose_count = $commentRepo->countOpposes($comment->id); $comment->update(); $counterCache->rebuild($comment->id); } else { $counter = $counterCache->get($comment->id); if ($counter) { $comment->reply_count = $counter['reply_count']; $comment->agree_count = $counter['agree_count']; $comment->oppose_count = $counter['oppose_count']; $comment->update(); } } } $this->redis->sRem($key, ...$commentIds); } protected function getCacheKey() { $syncer = new CommentCounterSyncer(); return $syncer->getSyncKey(); } protected function checkEnableRecount() { $config = $this->getDI()->get('config'); return $config['recount_comment'] ?? false; } }