memcache的缓存使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41179401/article/details/84848453

                            memcache的缓存使用

当有用户访问网页后会对请求的内容生成缓存,当有用户通过操作对数据库写入数据后会删除缓存从数据库里取出新的内容,并生成缓存。

示例图:

代码:

<?php
// 链接数据库
try{
    $pdo = new PDO('mysql:host=localhost;dbname=test','root','lmm13637064637');
}catch(PDOException $e){
    exit($e->getMessage());
}
$pdo->query('SET NAMES UTF8');
$sql = "SELECT username FROM user";
$rows = $pdo->query($sql);

//实例化memcache对象
$mem = new memcache();
$mem->addServer('127.0.0.1',11211);
//如果数据改变时
if(isset($_POST['send'])&&isset($_POST['username'])){
    $user = $_POST['username'];
    $pass = sha1($_POST['password']);
    $sql = "INSERT INTO user (username,password)VALUES('{$user}','{$pass}')";

    $tmp = $pdo->prepare($sql);
    $tmp->execute();
    if($tmp->rowCount()){
        //先删除缓存
        $mem->delete('list');
        exit("<script>location.href='b.php';</script>");
   }
}
?>
<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <title>memcached</title>
</head>
<body>
<form method="post">
        <input type="text" name="username" placeholder="请输入用户名">
        <input type="password" name="password" placeholder="请输入密码">
        <input type="submit" name="send" value="注册">
</form>
<hr>
<p>以下是网站的所有用户</p>
<hr>
<?php
        //如果有缓存直接取缓存
        $data = $mem->get('list');
        if($data){
            //有缓存
            echo '有缓存'.'<hr/>';
            $data =$mem->get('list');
        }else{
         //没有缓存则生成缓存
            echo '没有缓存=>生成缓存'.'<hr>';
            $data = $rows->fetchAll();
            $mem->set('list',$data,0);
        }
        //得到所有值
        foreach($data as $k=>$v){
           echo  $data[$k]['username'].'<br>';
        }


?>
</body>
</html>

 PS:在操作前要先开启memcache服务

 /usr/bin/memcached -d -l 127.0.0.1 -p 11211 -m 100 -u nobody

猜你喜欢

转载自blog.csdn.net/qq_41179401/article/details/84848453