簡體   English   中英

如何在php中為json api實現緩存系統

[英]How to implement cache system in php for json api

我的網站上有一些自定義社交按鈕,我可以使用API​​中的json獲取共享編號/關注者編號。 我試圖實現一個緩存系統來減少加載時間,並消除因過度使用API​​而被“標記為紅色”的風險。 但是,我在這方面沒有成功,主要是因為我不太了解整合步驟。 我希望有人可以幫我集成緩存系統。

以下是Twitter,Google Plus和Instagram的php代碼:

  • 推特
ob_start();
    $twittershare = 'http://cdn.api.twitter.com/1/urls/count.json?url='.$product["href"] .'';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $twittershare);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $jsonstring = curl_exec($ch);
    curl_close($ch);
    $bufferstr = ob_get_contents();
    ob_end_clean();
    $json = json_decode($bufferstr);

    echo $json->count;
  • Google Plus
$url = ''.$product["href"] .'';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://clients6.google.com/rpc?key=xxxxxxxxxx");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $curl_results = curl_exec($ch);
    curl_close($ch);
    $json = json_decode($curl_results, true);
    $count = intval($json[0]['result']['metadata']['globalCounts']['count']);
    $data = array();
    $data['plus_count'] = (string) $count;
    $data['url'] = $url;
    echo $data['plus_count'];
  • Instagram(取得粉絲數)
ob_start();
    $insta = 'https://api.instagram.com/v1/users/00000000?access_token={token}';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $insta);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $jsonstring = curl_exec($ch);
    curl_close($ch);
    $bufferstr = ob_get_contents();
    ob_end_clean();
    $json = json_decode($bufferstr);

    echo $json->data->counts->followed_by;

希望你們能夠一步一步地指導我如何為上面的代碼片段實現緩存系統。

好吧,正如我在評論中提到的,我會使用Memcached和一個數據庫,但是我將草擬一個僅限數據庫的解決方案(使用PDO for twitter)並將Memcached部分作為獎勵練習。 ;)我將通過AJAX加載關注者信息,以減少頁面加載時間,例如需要更新關注者計數。

我將使用以下數據庫模式:

CREATE TABLE IF NOT EXISTS `Followers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(100) NOT NULL,
  `data` longtext NOT NULL,
  `followers` int(5) NOT NULL,
  `last_update` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

首先,我定義了一個接口,因此您不依賴於任何實現:

interface SocialFollowers
{
    public function getFollowers();
}

然后,對於twitter共享API,我有一個實現類,它獲取數據庫句柄和初始化的目標URL。 使用檢索到的數據(如果可用)填充類屬性。 如果時間戳足夠新,您將立即獲得關注者數量,否則將查詢API,存儲結果,然后檢索關注者數量。

class TwitterFollowers implements SocialFollowers
{
    private $data = null;
    private $url = "";
    private $db = null;
    private $followers = null;

    protected $shareURL = "https://cdn.api.twitter.com/1/urls/count.json?url=";

    public function __construct($db, $url) {
        // initialize the database connection here
        // or use an existing handle
        $this->db = $db;

        // store the url
        $this->url = $url;

        // fetch the record from the database
        $stmt = $this->db->prepare('SELECT * FROM `Followers` WHERE url = :url ORDER BY last_update DESC LIMIT 1');
        $stmt->bindParam(":url", $url);
        $stmt->execute();

        $this->data = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!empty($this->data))
            $this->followers = $this->data["followers"];
    }

    public function getFollowers()
    {
        // create a timestamp that's 30 minutes ago
        // if it's newer than the value from the database -> call the api
        $old = new DateTime();
        $old->sub(new DateInterval("PT30M"));

        if (is_null($this->followers) || (new DateTime($this->data["last_update"]) < $old) ) {
            return $this->retrieveFromAPI();
        }

        return $this->followers;
    }

    private function retrieveFromAPI()
    {
        // mostly untouched
        ob_start();
        $twittershare = $this->shareURL . $this->url;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $twittershare);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $jsonstring = curl_exec($ch);
        curl_close($ch);
        $bufferstr = ob_get_contents();
        ob_end_clean();
        $json = json_decode($bufferstr);

        $this->followers = $json->count;

        // store the retrieved values in the database
        $stmt = $this->db->prepare('INSERT INTO Followers (url, data, followers)'
            .'VALUES (:url, :data, :followers)');
        $stmt->execute(array(
            ":url" => $this->url,
            ":data" => $bufferstr,
            ":followers" => $this->followers
        ));

        return $this->followers;
    }
}

對於Facebook,Google +,下一個社交網絡,您只需添加另一個實現。

請記住,此代碼未經過測試。 它錯過了PDO查詢的一些try / catch塊,並且還有改進的余地(例如:缺少某種鎖定機制以防止同時檢索同一URL,是否需要存儲返回的blob等)。

希望這對你有所幫助。

[edit]我稍微更新了代碼(修復了一些拼寫錯誤和轉換問題)並對其進行了測試。 你可以在github找到一個工作版本。 所有缺少的是ajax片段(假設jQuery)

$.ajax({
    url: "http://example.com/twitter.php",
    type: "get",
    data: {url: "http://stackoverflow.com"}
    success: function(data, textStatus, jqXHR) {
        // Update the corresponding counter like
        // $("#twitterfollowers").text(data);
        console.log(data);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM