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.macau-airport.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数据
}

猜你喜欢

转载自www.cnblogs.com/zhaoxiaowei/p/10587757.html