PHP中使用memcache

数据库(select)读出来的数据使用memcache

在会话控制session中使用

<?php

$mem=new Memcache;

$mem->connect("localhost",11211);

 

$sql="select * from saisai";

$mysqli=new mysqli("192.168.211.128","root","","test");

$result=$mysqli->query($sql);

$data=array();

while($row=$result->fetch_assoc()){

$data[]=$row;

}

$result->free();

$mysqli->close();

 

echo '<pre>';

print_r($data);

echo '</pre>';

?>

 

<?php

$mem=new Memcache;

$mem->connect("localhost",11211);

$data=$mem->get("shops");

 

if(!$data){

$sql="select * from saisai";

$mysqli=new mysqli("192.168.211.128","root","","test");

$result=$mysqli->query($sql);

$data=array();

while($row=$result->fetch_assoc()){

$data[]=$row;

}

$result->free();

$mysqli->close();

 

$mem->set("shops",$data,MEMCACHE_COMPRESSED,3600);

echo $sql;

}

echo '<pre>';

print_r($data);

echo '</pre>';

 

$mem->close();

?>

使用memcache缓存数据库内容,第一遍要查找数据库,并输出sql语句,以后就不用查找了。

 

 

memcache安全性:

1、内网设置memcache:只允许211.1访问

Memcache -d -u root -192.168.211.1 -p 11211

2、使用防火墙:允许211的访问

Iptables -A input -p tcp -s 192.168..211.1 --dport 11211 -j ACCEPT //


使用memcached 的因素:

--如果是一个小网站,pv值不大,就不考虑使用memcache

--变化频繁,查询频繁,但是不一定写入数据库(适合memcached)(用户在线状态.)

--变化频繁一变化就要入库[比如股票,金融.](不适合memcached)

--变化不频繁,查询频繁,不管如不入库,都比较适合memcache(新浪的新闻频道)