diff --git a/app/common/repositories/store/product/SpuRepository.php b/app/common/repositories/store/product/SpuRepository.php index 1939abaa..ed5ec943 100644 --- a/app/common/repositories/store/product/SpuRepository.php +++ b/app/common/repositories/store/product/SpuRepository.php @@ -177,18 +177,21 @@ class SpuRepository extends BaseRepository app()->make(UserVisitRepository::class)->searchProduct($this->userInfo ? $this->userInfo['uid'] : 0, $where['keyword'], (int)($where['mer_id'] ?? 0)); } } + if ($rand) { + $dataKey = 'CloudMerchantSpu_' . $where['mer_id']; $RedisCacheService = app()->make(RedisCacheService::class); - $exists=$RedisCacheService->exists('CloudMerchantSpu'.$where['mer_id']); - if ($exists){ - $Spu_arr=$RedisCacheService->SRANDMEMBER('CloudMerchantSpu'.$where['mer_id'], 10); - $where['product_id'] =$Spu_arr; - } else { - //TODO 后期优化随机查询 - $where['product_id'] = Db::name('cloud_product')->where('mer_id', $where['mer_id'])->where('status', 1)->orderRand()->limit(10)->column('product_id'); + $exists = $RedisCacheService->exists($dataKey); + if (!$exists) { + $productIds = Db::name('cloud_product')->where('mer_id', $where['mer_id'])->where('status', 1)->limit(100)->column('product_id'); + foreach ($productIds as $productId) { + $RedisCacheService->SADD($dataKey, $productId); + } } + $where['product_id'] = $this->getSpuFromCache($where['mer_id'], $page); unset($where['mer_id']); } + $entryMerId = $where['entry_mer_id'] ?? ''; unset($where['entry_mer_id']); $query = $this->dao->search($where); @@ -210,6 +213,37 @@ class SpuRepository extends BaseRepository } return compact('count', 'list'); } + + /** + * 从缓存中随机取出不重复数据 + * @param $merId + * @param $page + * @return array + */ + public function getSpuFromCache($merId, $page): array + { + $dataKey = 'CloudMerchantSpu_' . $merId; + $takenKey = 'CloudMerchantSpuTakenProductIds_' . $merId . '_page_'. $page; + $RedisCacheService = app()->make(RedisCacheService::class); + if (!$RedisCacheService->exists($takenKey)) { + $productIds = $RedisCacheService->sRandMember($dataKey, 10); + } else { + $keys = $RedisCacheService->sDiff($dataKey, $takenKey); + $number = min(count($keys), 10); + if ($number <= 0) { + return []; + } + $indexes = array_rand($keys, $number); + $productIds = []; + foreach ($indexes as $index) { + $productIds[] = $keys[$index]; + } + } + $RedisCacheService->sAdd($takenKey, ...$productIds); + $RedisCacheService->expire($takenKey, 60); + return $productIds; + } + public function getBorderList($list) { $make = app()->make(StoreActivityRepository::class);