If you don't know what memcached is, ask uncle google ; )
In short it's a memory caching system that allows to reduce database load by putting values into RAM.
Ok so installation on debian/ubuntu is as simple as that :
sudo apt-get install memcached php5-memcached
Afret installation you can check if memcached is working:
netstat -tap | grep memcached
You should get something like this:
tcp 0 0 localhost:11211 *:* LISTEN 1547/memcached
By default deamon is listening on port 11211
You can change it by modifying config file :
/etc/memcached.conf
If everything works fine we can try it out :)
You put value in cache by using '
set' method
to read the value you have to know the key name and use '
get' method.
m = new Memcached;
$m->addServer('127.0.0.1', 11211);
$foo = "foo";
$m->set('f',$foo);
var_dump($m->get('f'));
$m->delete('f');
var_dump($m->get('f'));
output:
string(3) "foo"
bool(false)
Ok so the same with query :
$sql = "select count(id) as count from test.test";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$count = $row['count'];
var_dump($count);
$m->set(md5($sql),$count);
var_dump($m->get(md5($sql)));
output:
string(1) "7"
string(1) "7"
So now we can create simple caching function :
function memQuery($sql,$m){
$key = md5($sql);
var_dump($m->get($key));
if($m->get($key)===FALSE){
echo "mysql:";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$m->set($key,$row);//store the result
return $row;
}else{
echo "mysql:";
return $m->get($key);
}
}
In next part I'm gonna show some administration issues.
Brak komentarzy:
Prześlij komentarz