mirror of
https://gitee.com/koogua/course-tencent-cloud.git
synced 2025-06-22 03:32:47 +08:00
88 lines
1.8 KiB
PHP
88 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Tasks;
|
|
|
|
use App\Caches\ConsultCounter as ConsultCounterCache;
|
|
use App\Library\Cache\Backend\Redis as RedisCache;
|
|
use App\Repos\Consult as ConsultRepo;
|
|
use App\Services\Syncer\ConsultCounter as ConsultCounterSyncer;
|
|
|
|
class SyncConsultCounterTask extends Task
|
|
{
|
|
|
|
/**
|
|
* @var RedisCache
|
|
*/
|
|
protected $cache;
|
|
|
|
/**
|
|
* @var \Redis
|
|
*/
|
|
protected $redis;
|
|
|
|
public function mainAction()
|
|
{
|
|
$this->cache = $this->getDI()->get('cache');
|
|
|
|
$this->redis = $this->cache->getRedis();
|
|
|
|
$this->rebuild();
|
|
}
|
|
|
|
protected function rebuild()
|
|
{
|
|
$key = $this->getCacheKey();
|
|
|
|
$consultIds = $this->redis->sRandMember($key, 500);
|
|
|
|
if (!$consultIds) return;
|
|
|
|
$consultRepo = new ConsultRepo();
|
|
|
|
$consults = $consultRepo->findByIds($consultIds);
|
|
|
|
if ($consults->count() == 0) {
|
|
return;
|
|
}
|
|
|
|
$counterCache = new ConsultCounterCache();
|
|
|
|
$allowRecount = $this->allowRecount();
|
|
|
|
foreach ($consults as $consult) {
|
|
|
|
if ($allowRecount) {
|
|
|
|
$consult->like_count = $consultRepo->countLikes($consult->id);
|
|
$consult->update();
|
|
|
|
$counterCache->rebuild($consult->id);
|
|
|
|
} else {
|
|
|
|
$counter = $counterCache->get($consult->id);
|
|
|
|
if ($counter) {
|
|
$consult->like_count = $counter['like_count'];
|
|
$consult->update();
|
|
}
|
|
}
|
|
}
|
|
|
|
$this->redis->sRem($key, ...$consultIds);
|
|
}
|
|
|
|
protected function getCacheKey()
|
|
{
|
|
$syncer = new ConsultCounterSyncer();
|
|
|
|
return $syncer->getSyncKey();
|
|
}
|
|
|
|
protected function allowRecount()
|
|
{
|
|
return date('H') % 4 == 0;
|
|
}
|
|
|
|
}
|