Thanks for sharing!

On Sunday, November 18, 2012 2:44:02 AM UTC-8, Niro wrote:
>
> Hi Guys,
>
> I thought you can benefit so I share this with the community.
>
> A few months ago I noticed that calls to Scalr DNS such as : 
> $memcache->addServer("ext-memcached.memcached.yourdomain.net",11211); 
> that happen on every script hit cost a lot in resources since the DNS can 
> take up to a couple of seconds. Remember you have this also for databases 
> etc...
>
> So I wrote the function below which uses APC (on php) to cache the IP in a 
> smart and efficient way.
> This reduced my servers load from average of around 3 with peaks of around 
> 16 to Zero (on a server doing ~100 hits/sec )
>
>
> Sample usage: $memcache->addServer(dns_resolve_cached_new("
> ext-memcached.memcached.yourdomain.net"),11211);
>
> Use at your own risk. See attached image for the effect in my case 
>
> Enjoy
>
> Nir B
>
>
>
> // dns_resolve_cached_new 
>
> // use APC to cache the ip address for servers like mysql and memcache 
>
> // Handles multiple ip addresses for the same url (such as in multiple 
> mysql slaves case) 
>
> // every 10 seconds fetch IP address again and update APC so other threads 
> wont fetch also
>
> function dns_resolve_cached_new($url){
>     $now=time();
>     $prefix='dnscache';  // so new version could work with older one
>
>     $ips_array=apc_fetch($prefix.$url); // ips_array[ips][ip_addr]=last 
> update;  ips_array['checketime']=[timestamp for next check]
>
>     if (empty ($ips_array['ips']) || ($now > $ips_array['checktime']) ) { // 
> every X seconds fetch ip from DNS
>
>         // immediately write to APC so other threads wont fetch IP as well
>         $ips_array['checktime']=$now+10; // check again in 10 secs;
>         apc_store ($prefix.$url, $ips_array, 1000);
>
>         // fetch IP address from DNS
>         $ip=gethostbyname($url);
>         $ips_array['ips'][$ip]=$now;
>
>         // if any of the ip addresses didnt get updated for the last 100 secs 
> discard it
>         foreach ($ips_array['ips'] as $tmp_ip=>$update_time) 
>             if (($now-$update_time) > 100 ) unset 
> ($ips_array['ips'][$tmp_ip]);
>
>         apc_store ($prefix.$url, $ips_array, 1000); // store updated (with 
> new refresh timestamp and without discarded ips)
>     }
>
>     // get random ip if multiple ips for the url (multiple mysql slaves for 
> example)
>      return array_rand($ips_array['ips']);
> }
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"scalr-discuss" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/scalr-discuss/-/MoSePa9VXicJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/scalr-discuss?hl=en.

Reply via email to