2010-09-24 21 views

Respuesta

2

Memcache su html y luego hacer algo como esto:

$memcache = memcache_connect('localhost', 11211); 

$page = $memcache->get('homepage'); 
if($page == ""){ 
    $mtime = microtime(); 
    $page = get_home(); 
    $mtime = explode(" ",$mtime); 
    $mtime = $mtime[1] + $mtime[0]; 
    $endtime = $mtime; 
    $totaltime = ($endtime - $starttime); 
    memcache_set($memcache, 'homepage', $page, 0, 30); 
    $page .= "\n<!-- Duly stored ($totaltime) -->"; 
} 
else{ 
    $mtime = microtime(); 
    $mtime = explode(" ",$mtime); 
    $mtime = $mtime[1] + $mtime[0]; 
    $endtime = $mtime; 
    $totaltime = ($endtime - $starttime); 
    $page .= "\n&lt;!-- served from memcache ($totaltime) -->"; 
} 
die($page); 
13

Mi preferencia es usar un proxy inverso de almacenamiento en caché, como Varnish.

En cuanto a una solución pura de PHP, podría tener algún código al final de su secuencia de comandos que almacena en caché el resultado final, y el código al principio que verifica si la página está en caché. Si la página se encontró en el caché, envíela y salga en lugar de ejecutar las consultas nuevamente.

<?php 

function cache_file() { 
    // something to (hopefully) uniquely identify the resource 
    $cache_key = md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']); 
    $cache_dir = '/tmp/phpcache'; 

    return $cache_dir . '/' . $cache_key; 
} 

// if we have a cache file, deliver it 
if(is_file($cache_file = cache_file())) { 
    readfile($cache_file); 
    exit; 
} 

// cache via output buffering, with callback 
ob_start('cache_output'); 

// 
// expensive processing happens here, along with page output. 
// 

function cache_output($content) { 
    file_put_contents(cache_file(), $content); 
    return $content; 
} 

Obviamente esto tiene un montón de personalización para su configuración, incluyendo la caducidad de la caché, un $cache_key que satisfaga sus necesidades, y la detección de error de páginas tan malo no se almacenan en caché.

+0

¿A dónde llama 'cache_output'? –

+1

@AakilFernandes El buffer de salida tiene un color implícito al final de la solicitud. 'ob_start()' especifica 'cache_output()' como su devolución de llamada. Entonces, la descarga implícita al final llama 'cache_output()'. –

17

Estoy usando phpFastCache (para alojamiento compartido, si no desea tocar php.ini y root para configurar memcached). Mira el menú de ejemplo. Tienen un ejemplo completo y muy fácil.

Primero establezca con phpFastCache :: set y luego obtenga con phpFastCache :: get - DONE!

Ejemplo: Reducir bases de datos llama

Su sitio web tiene 10.000 visitantes que están en línea, y la página dinámica que enviar 10.000 mismas consultas a la base de datos en cada carga de página. Con phpFastCache, su página solo envía 1 consulta a DB, y utiliza el caché para atender a otros 9,999 visitantes.

<?php 
    // In your config file 
    include("php_fast_cache.php"); 
    phpFastCache::$storage = "auto"; 
    // you can set it to files, apc, memcache, memcached, pdo, or wincache 
    // I like auto 

    // In your Class, Functions, PHP Pages 
    // try to get from Cache first. 
    $products = phpFastCache::get("products_page"); 

    if($products == null) { 
     $products = YOUR DB QUERIES || GET_PRODUCTS_FUNCTION; 
     // set products in to cache in 600 seconds = 5 minutes 
     phpFastCache::set("products_page",$products,600); 
    } 

    OUTPUT or RETURN your $products 
?> 
+0

+1 para el ejemplo y uno que funciona con alojamiento compartido. ¡Aclamaciones! –

+0

¿cómo puedes usar esta clase? ¿Puedes responder mi pregunta? http://stackoverflow.com/questions/22116573/how-to-use-phpfastcache –

1
<?php 
    //settings 
    $cache_ext = '.html'; //file extension 
    $cache_time  = 3600; //Cache file expires afere these seconds (1 hour = 3600 sec) 
    $cache_folder = 'cache/'; //folder to store Cache files 
    $ignore_pages = array('', ''); 

    $dynamic_url = 'http://'.$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']; // requested dynamic page (full url) 
    $cache_file  = $cache_folder.md5($dynamic_url).$cache_ext; // construct a cache file 
    $ignore = (in_array($dynamic_url,$ignore_pages))?true:false; //check if url is in ignore list 

    if (!$ignore && file_exists($cache_file) && time() - $cache_time < filemtime($cache_file)) { //check Cache exist and it's not expired. 
     ob_start('ob_gzhandler'); //Turn on output buffering, "ob_gzhandler" for the compressed page with gzip. 
     readfile($cache_file); //read Cache file 
     echo '<!-- cached page - '.date('l jS \of F Y h:i:s A', filemtime($cache_file)).', Page : '.$dynamic_url.' -->'; 
     ob_end_flush(); //Flush and turn off output buffering 
     exit(); //no need to proceed further, exit the flow. 
    } 
    //Turn on output buffering with gzip compression. 
    ob_start('ob_gzhandler'); 
    ######## Your Website Content Starts Below ######### 
    ?> 
    <!DOCTYPE html> 
    <html> 
     <head> 
      <title>Page to Cache</title> 
     </head> 
      <body> 
       Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ut tellus libero. 
      </body> 
    </html> 
    <?php 
    ######## Your Website Content Ends here ######### 

    if (!is_dir($cache_folder)) { //create a new folder if we need to 
     mkdir($cache_folder); 
    } 
    if(!$ignore){ 
     $fp = fopen($cache_file, 'w'); //open file for writing 
     fwrite($fp, ob_get_contents()); //write contents of the output buffer in Cache file 
     fclose($fp); //Close file pointer 
    } 
    ob_end_flush(); //Flush and turn off output buffering 

    ?> 
1

Lo importante, a menudo pasado por alto cuando hay una discusión sobre el almacenamiento en caché, es la sincronización de procesos para evitar la carrera de hilo (ver: https://en.wikipedia.org/wiki/Race_condition).

El típico escenario de caché en PHP sin sincronización se ve así: si no tiene recursos en la memoria caché, o si el recurso está vencido, debe crearse y colocarse en la memoria caché. El primer subproceso/proceso que ocurre al encontrarse con dicha condición está tratando de crear recursos, y durante ese tiempo, otros subprocesos también crearán el recurso, lo que conduce a la carrera de subprocesos, el bloqueo de caché y el descenso de rendimiento.

El problema se magnifica por el número de subprocesos simultáneos y la carga de trabajo creada por la tarea de creación de recursos. En sistemas ocupados, puede ocasionar problemas graves.

Hay muy pocos sistemas de almacenamiento en caché para PHP que tengan en cuenta la sincronización.

Uno de ellos es php-no-slam-cache: https://github.com/tztztztz/php-no-slam-cache

Cuestiones relacionadas