本文共 794 字,大约阅读时间需要 2 分钟。
最近刚开始研究redis,就写了一个php 使用 redis 的缓存小实例,不喜勿喷
大致思路如下:
主要对新闻进行缓存
首先判断如果是第一次访问,则查询数据库,并存入redis;如果不是,则直接从redis中读取数据
我设置了一个inner来判断是否为第一次访问,并且设置了inner的有效期是60秒(例如新闻需要实时)
具体代码如下:
connect('127.0.0.1',6379);
$redis->auth('12345');
if($redis->get('inner')=='yes' || !$redis->get('inner')){
//第一次进入,需要缓存
//连接数据库进行查询
$db = new mysqli('127.0.0.1','root','root','table');
$sql = "select * from newsinfo";
$res = $db->query($sql);
while($new = mysqli_fetch_assoc($res)){
$news[] = $new;
}
//将数据存入redis的list中
$json=json_encode($news);
$redis->del('news');//把键值删除,防止重复
$redis->lPush('news', $json);
$redis->set('inner', 'no',60); //设置键值有效期为60秒
}else{
//从redis中取出数据
$json=$redis->lRange('news', 0, -1);
$news=json_decode($json[0],true);
}
?>
redis缓存实例
$v) { ?>
在直接访问数据库时的反应时间为
而第二次访问反应时间为
反应时间明显减少了
感谢阅读
若存在错误请批评指出
转载地址:http://pnncl.baihongyu.com/