目录
一、缓存穿透的解决方案
二、缓存击穿解决办法
三、缓存雪崩的解决办法
<?php
class getPrizeList {
/**
* redis实例
* @var \Redis
*/
private $redis;
/**
* @var string
*/
private $redis_key = '|prize_list';
/**
* 过期时间
* @var int
*/
private $expire = 30;
/**
* getPrizeList constructor.
* @param $redis
*/
public function __construct($redis)
{
$this->redis = $redis;
}
/**
* @return array|bool|string
*/
public function fetch()
{
$result = $this->redis->get($this->redis_key);
if(!isset($result)) {
//此处应该进行数据库查询...
//如果查询结果不存在,给其默认空数组进行缓存
$result = [];
$this->redis->set($this->redis_key, $result, $this->expire);
}
return $result;
}
}
<?php
class getPrizeList {
/**
* redis实例
* @var \Redis
*/
private $redis;
/**
* @var string
*/
private $redis_key = '|prize_list';
/**
* @var string
*/
private $setnx_key = '|prize_list_setnx';
/**
* 过期时间
* @var int
*/
private $expire = 30;
/**
* getPrizeList constructor.
* @param $redis
*/
public function __construct($redis)
{
$this->redis = $redis;
}
/**
* @return array|bool|string
*/
public function fetch()
{
$result = $this->redis->get($this->redis_key);
if(!isset($result)) {
if($this->redis->setnx($this->setnx_key, 1, $this->expire)) {
//此处应该进行数据库查询...
//$result = 数据库查询结果;
$this->redis->set($this->redis_key, $result, $this->expire);
$this->redis->del($this->setnx_key); //删除互斥锁
} else {
//其他请求每等待10毫秒重新请求一次
sleep(10);
self::fetch();
}
}
return $result;
}
}
<?php
class getPrizeList {
/**
* redis实例
* @var \Redis
*/
private $redis;
/**
* @var string
*/
private $redis_key = '|prize_list';
/**
* 缓存标记key
* @var string
*/
private $cash_key = '|prize_list_cash';
/**
* 过期时间
* @var int
*/
private $expire = 30;
/**
* getPrizeList constructor.
* @param $redis
*/
public function __construct($redis)
{
$this->redis = $redis;
}
/**
* @return array|bool|string
*/
public function fetch()
{
$cash_result = $this->redis->get($this->cash_key);
$result = $this->redis->get($this->redis_key);
if(!$cash_result) {
$this->redis->set($this->cash_key, 1, $this->expire);
//此处应该进行数据库查询...
//$result = 数据库查询结果, 并且设置的时间要比cash_key长,这里设置为2倍;
$this->redis->set($this->redis_key, $result, $this->expire * 2);
}
return $result;
}
}
上一篇