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(); $allowRecount = $this->allowRecount(); foreach ($comments as $comment) { if ($allowRecount) { $comment->reply_count = $commentRepo->countReplies($comment->id); $comment->like_count = $commentRepo->countLikes($comment->id); $comment->update(); $counterCache->rebuild($comment->id); } else { $counter = $counterCache->get($comment->id); if ($counter) { $comment->reply_count = $counter['reply_count']; $comment->like_count = $counter['like_count']; $comment->update(); } } } $this->redis->sRem($key, ...$commentIds); } protected function getCacheKey() { $syncer = new CommentCounterSyncer(); return $syncer->getSyncKey(); } protected function allowRecount() { return date('H') % 4 == 0; } }