## 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
<?phpconst dsn="mysql:host=localhost;dbname=test";classdb{public$pdo;function__construct(){$this->pdo=newPDO(dsn,"root","123123");}functiongetData($where,$tbName,$returnSql=false){$whereStr="";foreach($whereas$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();}functionsaveToDB($data,$tbName,$returnSql=false){//$tbName,做的一个通用的SQL拼凑, 没做任何关键字过滤和危险字符过滤//$sql=true 则返回SQL,不执行$sql_fields="";$sql_values="";foreach($dataas$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);// 返回受影响的行}}