PHP Redis 緩存數據


// 注:只是在此做下記錄,有興趣的可以參考,不做實際教程文檔
// 配置文件
define('CONFIG', [
'redis-server' => '127.0.0.1',
'redis-port' => 6379,
'prod-name' => 'air-port-query',
'ttl' => 60,// 緩存過期時間為一分鍾
]
);
// redis 客戶端實例化
$redis = new Redis();
$redis->connect(CONFIG['redis-server'], CONFIG['redis-port']); //連接Redis
// 存儲key: "air-port-query:[type]:[lang]" 做為key存取
$prodKey = CONFIG['prod-name'];
$redisKey = "{$prodKey}:{$type}:{$lang}";

$data = $redis->get($redisKey);// 通過key獲取存入Redis中的數據
if (!$data) { // 判斷是否獲取到數據,如果獲取到數據證明緩存還沒過期,如果沒有獲取到數據證明緩存已過期,這個時候需要更新redis的數據
    try {
$data = file_get_contents("http://www.xxxxxxxxx.com/airportapps/api.php?type={$type}&lan={$lang}"); //拿到數據
} catch (\Exception $e) {
throw new Exception("Remote api error", 2);
}
$redis->setex($redisKey, CONFIG['ttl'], $data);// 存入json字符串,更新redis數據
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM