在PHP中什么情况下使用memcache
1.数据库读出来的数据(select)使用memcache处理;
2.在会话控制中使用memcache。
这里我主要总结第一点,数据库读出来的数据怎样使用memcache。
实例化memcache对象
$mem = new Memcache;
建立连接
$mem->connect("localhost", 11211);
还可以添加服务器
$mem->addSever("www.xxxx.com", 11211);
$mem->addSever("121.12.32.35", 11211);
保存字符串类型的数据
$mem->add("mystr", "This is a memcache test.", MEMCACHE_COMPRESSED, 3600);
保存数组类型的数据
$mem->add("myarr", array("aaa", "bbb", "ccc"), MEMCACHE_COMPRESSED, 3600);
注:MEMCACHE_COMPRESSED,一个常量,用于标记对数据进行压缩(使用zlib)。
取出保存的数据
$str = $mem->get("mystr");
$arr = $mem->get("myarr");
将数据库中读出的数据保存进memcache
$key = "list"; //如果同一个项目安装两次,key要有前缀
$data = $mem->get($key); //从memcache提取
if(!$data){ //判断所需数据是否保存进memcache
//以下为将数据库中读出的数据保存进memcache的代码
$sql = "select * from db_infoclass";
$mysqli = new mysqli("localhost", "root", "root", "demo");
$result = $mysqli->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
$result->free();
$mysqli->close();
$mem->set($key, $data, MEMCACHE_COMPRESSED, 3600);
}
关闭memcache
$mem->close();
更多memcache类方法参考:PHP:memcache