【发布时间】:2020-06-19 02:41:54
【问题描述】:
我需要缓存 Steam API 解析的结果。所以缓存的结果会持续 15 分钟。我有一个代码:
public function load()
{
if (Auth::guest()) return response()->json(['success' => false, 'msg' => 'You need login!']);
$inventory = $this->getInventory(file_get_contents('http://steamcommunity.com/inventory/' . $this->user->steamid64 . '/570/2?l=russian&count=5000', true));
if (!$inventory) {
return response()->json(['success' => false, 'msg' => 'Error']);
}
$items = [];
$items_with_prices = json_decode(\Storage::get('prices.txt'));
$items_with_prices_by_key = [];
foreach ($items_with_prices->items as $item_price_key => $item_price_data) {
$items_with_prices_by_key[$item_price_key] = $item_price_data->price;
}
foreach ($inventory['rgInventory'] as $info) {
$item = $inventory['rgDescriptions'][$info['classid'] . '_' . $info['instanceid']];
if ($item['tradable'] == 0) continue;
$price = 0;//InventoryController::getItemPrice($item['market_hash_name']);
if (array_key_exists($item['market_hash_name'], $items_with_prices_by_key)) {
$price = $items_with_prices_by_key[$item['market_hash_name']];
}
if (!$price) continue;
if ($price < 1) $price = 0.64;
$type = $this->getType($item['type']);
$items[] = [
'id' => $info['id'],
'classid' => $item['icon_url'],
'price' => round($price, 2),
'type' => $type
];
}
usort($items, function($a, $b){
return ($b['price'] - $a['price']);
});
return response()->json(['success' => true, 'items' => $items]);
}
此代码仅在站点用户单击“显示我的项目”按钮并向 Steam Dota 2 中的用户项目列表发送请求时有效。现在,如果不断单击以获取项目列表,Steam 可以阻止服务器的 IP 地址 24 小时。据我了解,我需要将$inventory 变量的结果放入缓存中。我用字段id、user_id、items、date 创建数据库表cache。
我现在如何缓存 $inventory 15 分钟变量的结果?
【问题讨论】:
-
你为什么不把创建时间和你创建的数据库一起添加,每次检查差异是否大于 15 分钟,然后从 api 获取,否则从 db 获取。
-
为什么要删除旧问题?我给了你一个有效的逻辑来解决这个问题。