PHP緩衝使用的一個陷阱_PHP教程

來源:互聯網
上載者:User
先看一段代碼:
[php]
/**
* 擷取設定資訊
*/
public function getCoinSetting() {
$cache = Common::getTair();
$ckey = Common::hashKey("Hello");
$ret = $cache->get($ckey);
if ($ret) return json_decode($ret, true);
$taomanyiApiService = $this->_getTmiApiService();
$result = $taomanyiApiService->getCoinSetting();
$cache->set($ckey, json_encode($result), 3600);
return $result;
}

這是一個使用Tair記憶體緩衝的執行個體,這段代碼中,設定了緩衝,緩衝時間為3600秒。資料是從Api中擷取的,如果這麼寫會出現什麼問題呢?假如:
[php]
$result = $taomanyiApiService->getCoinSetting();

$result擷取的資料為空白,因為$result資料是從HTTP請求過來的,資料不正常也是比較常見的事情。在這種狀況下,HTTP請求失敗,那麼介面資料就請求不到,接下來的流程是設定緩衝
[php ]
$cache->set($ckey, json_encode($result), 3600);

我們會發現,因為一次介面HTTP請求的失敗,我們不小心將空資料緩衝了起來,緩衝時間為3600秒。這樣就會出現頁面上,例如分類出現了資料的空白,影響了整個商務程序
我們做以下的最佳化:
[php]
if ($result) $cache->set($ckey, json_encode($result), 3600);


作者:initphp

http://www.bkjia.com/PHPjc/478077.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/478077.htmlTechArticle先看一段代碼: [php] /** * 擷取設定資訊 */ public function getCoinSetting() { $cache = Common::getTair(); $ckey = Common::hashKey(Hello); $ret = $cache-get($ckey); if...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.