Selasa, 18 Desember 2012



Contoh penggunaan Memcache untuk  menyimpan data.
<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

$key = "Test"; // Nama unique key yang akan disimpan (cache) di cluster memory
$cache_result = array();
$cache_result = $memcache->get($key); // nama object Memcached

if($cache_result){
    // Jika request kedua (sudah di cache di awal)
    $result=$cache_result;
}else{
    // Jika request pertama ambil data dari database lalu distribusikan di memory server
    $con = ocilogon("scott","tiger","orcl");
    $sql ="SELECT * FROM EMP";
    $sql = ociparse($con,$sql);
    ociexecute($sql);
   
    while(ocifetch($sql))
    $result[]=ociresult($sql,"EMPNO"); // penyimpanan hasil query didalam array
    $memcache->set($key, $result, MEMCACHE_COMPRESSED, 600); // disimpan 600 detik atau 10 menit dengan nama key $key
}

//Menampilkan data
foreach($result as $r){
    echo "$r<br/>";
}

?>

Hasil dari file diatas, maka empno akan disimpan selama 10 menit.


Needed Files
·         memcached.exe Direct Link
·         MSVCP71.DLL Windows DLL Files
·         msvcr71.dll
·         php_memcache.dll Working memcache for PHP 5.3.4
Steps
1.     Copy MSVCP71.DLL, msvcr71.dll to C:\windows\system32
2.     Copy memcached.exe into C:\memcached
3.     Run Command Prompt as Administrator
4.     type: C:\memcached\memcached.exe -d install
5.     type: C:\memcached\memcached.exe -d start
6.     Copy php_memcache.dll to C:\wamp\bin\php\php5.3.4\ext
7.     Restart Apache using Wamp controls
8.     Enable WAMP -> PHP -> PHP Extensios -> php_memcache
9.     Run this code to test the installation: 

<?php
    $memcache = new Memcache;
    $memcache->connect("localhost",11211); # You might need to set "localhost" to "127.0.0.1"

    echo "Server's version: " . $memcache->getVersion() . "<br />\n";

    $tmp_object = new stdClass;
    $tmp_object->str_attr = "test";
    $tmp_object->int_attr = 123;

    $memcache->set("key",$tmp_object,false,3600);
    echo "Store data in the cache (data will expire in 3600 seconds)<br />\n";

    echo "Data from the cache:<br />\n";
    var_dump($memcache->get("key"));
?>

If you see anything but errors, you are now using memcache!


Memcached, by default, loads with 64mb of memory for it’s use which is low for most applications. To change this to something else, navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached Server in your registry, find the ImagePath entry and change it to look something like this:
“C:\memcached\memcached.exe” -d runservice -m 512
Now when you start the service via net start “memcached Server”, it will run with 512mb of memory at it’s disposal.







Subscribe to RSS Feed Follow me on Twitter!