优化随机查询云仓商品

This commit is contained in:
luofei 2023-05-31 11:12:52 +08:00
parent 7ed8a2ea48
commit 3fa65222ee

View File

@ -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)); app()->make(UserVisitRepository::class)->searchProduct($this->userInfo ? $this->userInfo['uid'] : 0, $where['keyword'], (int)($where['mer_id'] ?? 0));
} }
} }
if ($rand) { if ($rand) {
$dataKey = 'CloudMerchantSpu_' . $where['mer_id'];
$RedisCacheService = app()->make(RedisCacheService::class); $RedisCacheService = app()->make(RedisCacheService::class);
$exists=$RedisCacheService->exists('CloudMerchantSpu'.$where['mer_id']); $exists = $RedisCacheService->exists($dataKey);
if ($exists){ if (!$exists) {
$Spu_arr=$RedisCacheService->SRANDMEMBER('CloudMerchantSpu'.$where['mer_id'], 10); $productIds = Db::name('cloud_product')->where('mer_id', $where['mer_id'])->where('status', 1)->limit(100)->column('product_id');
$where['product_id'] =$Spu_arr; foreach ($productIds as $productId) {
} else { $RedisCacheService->SADD($dataKey, $productId);
//TODO 后期优化随机查询
$where['product_id'] = Db::name('cloud_product')->where('mer_id', $where['mer_id'])->where('status', 1)->orderRand()->limit(10)->column('product_id');
} }
}
$where['product_id'] = $this->getSpuFromCache($where['mer_id'], $page);
unset($where['mer_id']); unset($where['mer_id']);
} }
$entryMerId = $where['entry_mer_id'] ?? ''; $entryMerId = $where['entry_mer_id'] ?? '';
unset($where['entry_mer_id']); unset($where['entry_mer_id']);
$query = $this->dao->search($where); $query = $this->dao->search($where);
@ -210,6 +213,37 @@ class SpuRepository extends BaseRepository
} }
return compact('count', 'list'); 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) public function getBorderList($list)
{ {
$make = app()->make(StoreActivityRepository::class); $make = app()->make(StoreActivityRepository::class);