Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memcached "Could not connect" error on peak hours

Tags:

php

memcached

i use memecached on my website (php, mysql, apache, ubuntu..) it work very fast but on "peak hours" i get a lot of "could not connect" error message, sometime users need to refresh 5 time for see the content.

I have 24 gb ram on my server and "top" command give me this for the memcached process:

4135 nobody    20   0  161m  37m  836 S    7 (%CPU)  0.2 (%MEM)   0:07.06 memcached

I launch memcached server like this:

memcached -d -u nobody -m 8192 -p 12000 -c 11212

And this is my PHP function:

<?
function cache_sql($query,$update,$time=0)
{

    $m = new Memcache;
    $m->connect('localhost', 11211) or die ("Could not connect");

    $file = $m->get(md5($query));

    if($update == 1)
    {
        $results = mysql_query($query);
        while($data = mysql_fetch_array($results)){$records[] = $data;}

        if(!$file)
        {
            $m->set(md5($query), $records, NULL, $time);
        }
        else
        {
            $m->replace(md5($query), $records, NULL, $time);
        }
    }
    else
    {
        if(!$file)
        {
            $results = mysql_query($query);
            while($data = mysql_fetch_array($results)){$records[] = $data;}

            $m->set(md5($query), $records, NULL, $time);
            return $records;
        }
        else
        {
            return $file;
        }
    }

}
?>

I am doing it right?

like image 227
Tahola Avatar asked Oct 26 '11 12:10

Tahola


1 Answers

I think you accidentally flipped the -c and -p parameters when starting memcached:

memcached -d -u nobody -m 8192 -p 11212 -c 12000
  • first, make sure you have the latest versions of the php pecl/memcache since there were a few bugs
  • Take a look at the logs, is there any error, or notice being reported on the connection failure?
  • take a look at /etc/memcached.conf; in particular MAXCONN - the number of connections
  • in a terminal use telnet 127.0.0.1 11211 and then type stats to see curr_connections and total_connections
  • currently you aren't using persistent connections which would speed things up, though I'm not sure it would necessarily help connecting. To use persistent connections:

replace

$m->connect('localhost', 11211) or die ("Could not connect");

with

$m->addServer('localhost', 11211) or die ("Could not connect");
  • also, I should point out that if your query often has different variables in the where clause, this kind of caching would always fail. You might want to log when a cache miss occurs
like image 88
uncreative Avatar answered Nov 03 '22 08:11

uncreative