Home > Article > Backend Development > PHP cache instance using redis
The content shared with you in this article is a caching example of PHP using redis. It has certain reference value. Friends in need can refer to it.
I just started to study redis recently and wrote a PHP application. A small example of redis caching, don’t complain if you don’t like it
The general idea is as follows:
Mainly cache news
First determine if it is the first visit, then Query the database and store it in redis; if not, read the data directly from redis
I set up an inner to determine whether it is the first access, and set the validity period of the inner to 60 seconds (for example News needs to be real-time)
The specific code is as follows:
<?php //实例化redis $redis = new \Redis(); //连接redis $redis->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); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>redis缓存实例</title> </head> <body> <?php foreach ($news as $k => $v) { ?> <li><?php echo $v['title']; ?></li> <?php } ?> </body> </html>
The response time when directly accessing the database is
And the The response time of the second visit is
The response time is significantly reduced
Related recommendations:
About the Redis command in PHP Part summary
php adds redis extension graphic and text explanation
30 code examples of commonly used methods of operating redis in php
The above is the detailed content of PHP cache instance using redis. For more information, please follow other related articles on the PHP Chinese website!