Pure LRU is not very good, as it caches all new keys, and I need to cache only 0.1% of the data (with high rating), so there will not be much unnecessary writing.
Of course, I will implement the Redis method, as suggested in the next version, as this should be much faster. Therefore, use this only if you do not have Redis, if you cannot decide to score any other than just counting hits for some time or simply if you want it to be simple.
But my best attempt is to use key => value memcached, just test now and look fast and stable. Before I thought wrong ...
When a new element needs to be cached, we check if there is an account in the cache (the cache for the key contains int), if yes and less than our limit, we increase the score, if yes and above the limit, we get the content and save the cache. If there is anything else in the cache besides the number, this is our content (high score). If the cache for the key does not exist at all, we save int 1 as an account in the cache with a very short TTL, and we just get the content without caching (low score).
<?php $minhits = 10; // Min 10 hits for one key $minhitstime = 60 // Max 60 seconds between hits $cachettl = 3600; // Cache for 3600 seconds $key = "article1"; $mem = new Memcached(); $mem->addServer('localhost', 11211); $content = $mem->get($key); if(!$content OR (is_int($content) AND $content<$minhits)){ $content = getArticleContent(); // Your own function } if(is_int($c)){ if($c>=$minhits){ $mem->set($key, $content, $cachettl); } else { $mem->set($key, ($c+1), $minhitstime); } } elseif($c) { $content = $c; } else { $mem->set($key, 1, $minhitstime); } echo $content; ?>
Also do not try to cache int-only values;) If so, you need to edit the code.