Redis 在项目中的使用

1. 新闻缓存:设置、查询、获取过期时间;

## 1. 简单的新闻缓存业务逻辑伪代码
# 实际这个代码是有很大漏洞与风险
String newsID=getParameter("id") ;
News getNews= getFromRedis("news"+newsID);
if(getNews==null)
{
    getNews=getFromDB(123);
    setToRedis("news"+newsID,getNews,expire);
}
response.write(getNews);

## 简单命令:
# 设置、获取
set key value
get key
# 设置 key 过期时间
expire key value
# 获取key的过期时间
ttl key  
# 查看所有key
keys * 

2. 缓存穿透处理:设置空键;

  • Entities/db.php
<?php
const  dsn="mysql:host=localhost;dbname=test";
class db{

    public $pdo;
    function __construct(){
        $this->pdo=new PDO(dsn,"root","123123");
    }

    function getData($where,$tbName,$returnSql=false){
        $whereStr="";
        foreach($where as $key=>$value){
            $whereStr.=" and ";
            if(is_int($value))
                $whereStr.=$key."=".$value;
            else
                $whereStr.=$key."='".$value."'";
        }
        $sql="select * from $tbName where 1=1 ".$whereStr;

        if($returnSql)
            return $sql;
        $sth = $this->pdo->prepare($sql);
        $sth->execute();

        $sth->setFetchMode(PDO::FETCH_ASSOC);
        return $sth->fetchAll();
    }
    
    function saveToDB($data,$tbName,$returnSql=false){
        //$tbName,做的一个通用的SQL拼凑, 没做任何关键字过滤和危险字符过滤
        //$sql=true 则返回SQL,不执行

        $sql_fields="";
        $sql_values="";
        foreach($data as $key=>$value){
        	//__开头的代表是内部变量
            if(strpos($key,"__")!==false && strpos($key,"__")===0) continue;
            //拼凑字符串
            if($sql_fields!="")
                $sql_fields.=",";
            $sql_fields.=$key;
            if($sql_values!="")
                $sql_values.=",";
            $sql_values.="'".$value."'";
        }

        $sql="insert into $tbName(".$sql_fields.") values(".$sql_values.")";

        if($returnSql)
            return $sql;
        return $this->pdo->exec($sql);// 返回受影响的行
    }
}
  • Entities/StringOperator.php
<?php
class StringOperator
{
    private   $redis=false;
     function __construct(Redis $redis){
          $this->redis=$redis;
     }
     
     function  getFromReids(String $key){
         return $this->redis->get($key);
     }
     
    function  setToRedis(String $key,String $value,int $expire=0){
        return $this->redis->set($key,$value,$expire);
    }
    
    function expireCache(String $key,int $expire=5) {
        $getExpire=$this->redis->ttl($key);
        if($getExpire<0) //已经过期
            $getExpire=0;
        $this->redis->expire($key,$expire+$getExpire);
    }
}
  • Entities/RedisObject.php
<?php
require("StringOperator.php");
class RedisObject{
    protected $redis_client;
    public $StringOperator;
    function __construct()
    {
        $this->redis_client=new Redis();
        $this->redis_client->connect("127.0.0.1",6379);
        $this->StringOperator=new StringOperator($this->redis_client);
    }
}
  • Entities/function.php
<?php
require("RedisObject.php");
require("db.php");
const defaultCache="-1"; //默认缓存,字符可以自己设置
// redis相关函数
$redis=new RedisObject();

function getParameter(String $p):int{
    if(isset($_GET[$p]))
      return $_GET[$p];
    return 0;
}

function getFromDB(String $newsid){
    $db=new db();
    return $db->getData(["news_id"=>$newsid],"news");
}

function isDefaultCache($c):bool{
    if(trim($c)==="-1")
        return true;
    return false;
}
  • Entities/NewsInfo.php
<?php
class NewsInfo{
    public $news_id;
    public $news_title;
}
  • news.php
<?php
require("Entities/functions.php");
require("Entities/NewsInfo.php");

$newsid=getParameter("id");
if(!$newsid) die("错误的参数");
$news=new NewsInfo();

$getNews=$redis->StringOperator->getFromReids("news".$newsid);  //从redis取

if(!$getNews) {
	//如果木有取到
    $getNews=getFromDB($newsid);//就从数据库取
    if(!$getNews) //数据库里也没取到
        $getNews=defaultCache; //设置为默认缓存
    else
        $getNews=json_encode($getNews);//DB取到了 就把它变成JSON格式字符串

	//塞入缓存 ,过期时间为200秒
    $redis->StringOperator->setToRedis("news".$newsid,$getNews,200);
}else{
    echo "from cache";
}

if(isDefaultCache($getNews)){
    $redis->StringOperator->expireCache("news".$newsid,5);// 给原来的缓存 增加5秒时间
    exit("别黑我了!!!");
}

echo $getNews;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值