一 安装memcache
具体流程这篇文章有写到: 点击 链接
二 在项目中应用memcache
为了减轻数据库的查询压力,所以我们把一些不经常变动的数据进行缓存,用户查询时,如果查询的要求是一样的,我们就memcache缓存中读取数据并返回去,如果查询要求变了,我们再到数据库中查询,并将查询结果缓存到memcache,以备下次有同样需求的时候,可以直接从memcache缓存中取出数据
原理:
我们将sql md5转换成32位字符串,作为key存到memcache, 并将sql查询的结果data作为对应的value存到memcache
代码部分:
function inquiry($sql,Memcache $memcache)
{$key = md5($sql);$data = $memcache->get($key);if(!$data) {try {$pdo = new PDO('mysql:dbname=test;host=localhost','root','root');} catch (PDOException $e){die("连接失败:".$e->getMessage());}$stmt = $pdo->prepare($sql);$stmt->execute();$data = $stmt->fetchAll(2);$memcache->add($key,$data,MEMCACHE_COMPRESSED,0);}Return $data;}$memcache = new Memcache;$memcache->connect('localhost',11211);$data = inquiry('select id,name,age,sex,edu,salary,city from student ',$memcache);Var_dump($data);
结果是可以正常显示的
array (size=39)0 => array (size=7)'id' => string '1' (length=1)'name' => string '周更生' (length=9)'age' => string '24' (length=2)'sex' => string '男' (length=3)'edu' => string '大专' (length=6)'salary' => string '5000.00' (length=7)'city' => string '山东省' (length=9)1 => array (size=7)'id' => string '2' (length=1)'name' => string '王小平' (length=9)'age' => string '28' (length=2)'sex' => string '男' (length=3)'edu' => string '大专' (length=6)'salary' => string '500.00' (length=6)'city' => string '陕西省' (length=9)2 => array (size=7)'id' => string '3' (length=1)'name' => string '周改娟' (length=9)'age' => string '28' (length=2)'sex' => string '女' (length=3)'edu' => string '大专' (length=6)'salary' => string '8000.00' (length=7)
(size=39)0 => array (size=7)'id' => string '1' (length=1)'name' => string '周更生' (length=9)'age' => string '24' (length=2)'sex' => string '男' (length=3)'edu' => string '大专' (length=6)'salary' => string '5000.00' (length=7)'city' => string '山东省' (length=9)1 => array (size=7)'id' => string '2' (length=1)'name' => string '王小平' (length=9)'age' => string '28' (length=2)'sex' => string '男' (length=3)'edu' => string '大专' (length=6)'salary' => string '500.00' (length=6)'city' => string '陕西省' (length=9)2 => array (size=7)'id' => string '3' (length=1)'name' => string '周改娟' (length=9)'age' => string '28' (length=2)'sex' => string '女' (length=3)'edu' => string '大专' (length=6)'salary' => string '8000.00' (length=7)
分析:
第一次从数据库中查询出数据,显示到浏览器,并将md5(sql)和查询结果data存储到memcache缓存中
第二次直接从缓存中读取出数据,显示到浏览器
注: 我们也可以登录memadmin 去查看是否将结果存到了memcache中。软件地址:【memcache客户端可视化管理软件】
这样,我们就完成了基本的memcache在项目中的应用