缓存 Instagram API 请求
Posted
技术标签:
【中文标题】缓存 Instagram API 请求【英文标题】:Cache instagram API request 【发布时间】:2015-01-24 12:16:01 【问题描述】:我正在实现一些来自 instagram 的照片,以在我的页脚中用作我 laravel 项目的装饰。但是当我刷新页面时,它会一遍又一遍地调用 api。我正在考虑将调用缓存或存储在会话中,这样我就不必总是发送 API 请求......那么我该如何缓存这个 api 请求?
php:
<?php
$clientid = "XXXXXXXXXXXXXXXXXXXXXXXX";
$url = "https://api.instagram.com/v1/tags/kittens/media/recent?client_id=".$clientid;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$results = json_decode(curl_exec($curl));
?>
html:
<footer>
<?php
echo "<ul class='inline-list'>";
foreach ($results->data as $result)
echo "<li><img src='".$result->images->thumbnail->url."'></li>";
echo "</ul>";
?>
</footer>
【问题讨论】:
那么您的问题是什么?如何缓存? 是的,我想知道如何缓存这个 api 请求 【参考方案1】:要缓存请求,您可以将其写入文件并检查修改日期或使用某种缓存库。
例如http://www.phpfastcache.com/
// In your config file
include("phpfastcache/phpfastcache.php");
phpFastCache::setup("storage","auto");
// phpFastCache support "apc", "memcache", "memcached", "wincache" ,"files", "sqlite" and "xcache"
// You don't need to change your code when you change your caching system. Or simple keep it auto
$cache = phpFastCache();
// In your Class, Functions, PHP Pages
// try to get from Cache first. product_page = YOUR Identity Keyword
$results = $cache->get("cache_instagram");
if($results == null)
$clientid = "XXXXXXXXXXXXXXXXXXXXXXXX";
$url = "https://api.instagram.com/v1/tags/kittens/media/recent?client_id=".$clientid;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$results = json_decode(curl_exec($curl));
// set products in to cache in 600 seconds = 10 minutes
$cache->set("cache_instagram", $results,600);
// Output Your Contents $products HERE
// Re-written first example from page for purpouse of your script.
对于 Laravel 内置缓存
// http://laravel.com/docs/4.2/cache
if (Cache::has('cache_instagram'))
$results = Cache::get('cache_instagram');
else
$clientid = "XXXXXXXXXXXXXXXXXXXXXXXX";
$url = "https://api.instagram.com/v1/tags/kittens/media/recent?client_id=".$clientid;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$results = curl_exec($curl);
Cache::put('cache_instagram', $results, 60); // 1 hour
$results = json_decode($results);
【讨论】:
它适用于 PHP。它的独立库。让我编辑答案 添加了有关内置 laravel 缓存的信息。但是,您没有在问题中写下您正在使用 laravel Raw Curl 是正确的解决方案。因为 guzzle 在我的案例中随机给出 SSL 错误(Laravel 5.4)。以上是关于缓存 Instagram API 请求的主要内容,如果未能解决你的问题,请参考以下文章