网站提速-缓存技术(5)

 PHP中使用memcachephp

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

在会话控制session中使用 sql

<?php 数据库

$mem=new Memcache; 缓存

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

 

$sql="select * from saisai"; session

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

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

$data=array(); memcached

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(新浪的新闻频道)

相关文章
相关标签/搜索