PHP cache instance using redis

不言
Release: 2023-03-23 16:48:01
Original
2802 people have browsed it

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(&#39;127.0.0.1&#39;,6379);
$redis->auth(&#39;12345&#39;); 
if($redis->get(&#39;inner&#39;)==&#39;yes&#39; || !$redis->get(&#39;inner&#39;)){
	//第一次进入,需要缓存
	//连接数据库进行查询
	$db = new mysqli(&#39;127.0.0.1&#39;,&#39;root&#39;,&#39;root&#39;,&#39;table&#39;);
	$sql = "select * from newsinfo";
	$res = $db->query($sql);
	while($new = mysqli_fetch_assoc($res)){
		$news[] = $new;
	}
        //将数据存入redis的list中
	$json=json_encode($news);
	$redis->del(&#39;news&#39;);//把键值删除,防止重复
    $redis->lPush(&#39;news&#39;, $json);
    $redis->set(&#39;inner&#39;, &#39;no&#39;,60); //设置键值有效期为60秒
}else{
	//从redis中取出数据
	$json=$redis->lRange(&#39;news&#39;, 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[&#39;title&#39;];  ?></li>
	<?php } ?>
</body>
</html>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template