项目中如何生成缓存?缓存过期时如何处理?数据库数据更新时如何同时更新缓存?
<?php
namespace DaiBk\Library;
class CacheClass{
/**
* @param string $method 类名称
* @param string $tag 缓存标签
* @param \Closure $func 闭包函数(获取数据库中数据)
* @param int $timeCache 过期时间(如果timeCache=0时,直接返回$func()的值并缓存至redis)
*/
public static function cacheDataByRedis($method, $tag, \Closure $func, $timeCache = 300){
//获取redis资源(我这里是从DI容器中获取,可以根据自己的情况获取redis)
$redis = (\Phalcon\DI::getDefault())->get('redis');
if(empty($method) || empty($tag)){
return $func();
}
$method = str_replace('\\', '_', $method);
$method = str_replace('::', '@', $method);
$now = time();
$timeCache = intval($timeCache) > 0 ? $timeCache : 0;
//根据method,tag生成缓存key值
$rKey = "BGCache:" . $method . ":" . $tag;
if($timeCache > 0){
$json_str = $redis->get($rKey);
$json = !empty($json_str) ? json_decode($json_str, true) : [];
$json['_update_'] = isset($json['_update_']) ? $json['_update_'] : 0;
$data = isset($json['data']) ? $json['data'] : [];
}
//缓存时间不允许超过timeCache(如果timeCache=0或者时间超过$timeCache,直接返回$func()的值并缓存至redis)
if($timeCache == 0 || !isset($json['data']) || $now - $json['_update_'] > $timeCache){
$data = $func();
$timeCache = $timeCache <= 0 ? 300 : $timeCache;
$redis->set($rKey, json_encode(['data' => $data, '_update_' => $now]), $timeCache);
}
return $data;
}
}
当我们使用的时候
$result = \DaiBk\Library\CacheClass::cacheDataByRedis(__METHOD__, $tag, function () use ($dataUserBasicInfo,$params){
return $dataUserBasicInfo->getUserBasicInfo($params); //这里返回的就是操作数据库的数据(当使用数据库更新操作时,将timeCache设置为0)
},3600);
return $result;
缓存是一把双刃剑,虽然性能比关系型数据库好很多,但是大量使用以后还是容易出现难以管理的情况,所以还是建议根据业务慎重使用.