Redis 缓存击穿,解决redis缓存击穿例子
public function getArticle($id)
{
$key = "article_content_".$id;
$ret = Redis::get($key);
if ($ret === null) {
//生成锁的key
$lockKey = $key . '_lock';
//生成随机数,用于设置锁的值,后面释放锁时会用到
$random = mt_rand();
//拿到互斥锁
if ($this->lock($lockKey, $random)) {
//这里是伪代码,表示从数据库中获取文章数据
$ret = json_encode(DB::table("article")->where("id",$id)->first());
//更新缓存,过期时间可以根据情况自已调整
Redis::set($key, json_encode($ret));
//释放锁
$this->unLock($lockKey, $random);
} else {
//等待200毫秒,然后重新获取缓存值,让其他获取到锁的进程取得数据并设置缓存
usleep(200);
return $this->getArticle($id);
}
}else{
$ret = json_decode($ret);
}
return $ret;
}
public function lock($key,$random)
{
$lock = Redis::set($key,$random,"nx","ex",10);
return $lock;
}
public function unlock($key,$random)
{
if (Redis::get($key) == $random){
Redis::del($key);
}
}本文由:xiaoshu168.com 作者:xiaoshu发表,转载请注明来源!