7

I have a page where few thousands of users can hit a method at the same time . I do have following code where I connect every time . Since this will go to a seperate memcache server will this cause slowdowns is there a way to connect just once and reuse that connection ? Do I have to close connection after every request ?

$primary_connected = $memcache_primary->connect($primary_memcache_server, 11211);
if($primary_connected){
        $data = $memcache_primary->get($key);
        if ($data != NULL) {
            return data;
        }
 }
else{
/////Get data from database 
}
Pit Digger
  • 9,618
  • 23
  • 78
  • 122

1 Answers1

4

If you are using the PHP memcached class (the one with the d on the end, not memcache) then yes, you can open a persistent connection.

You can pass a persistent ID to the constructor which will open a persistent connection and subsequent instances that use the same persistent ID will use that connection.

$memcached = new Memcached('method_name_or_persistent_identifier');
$memcached->addServer(...);
// use it

Hope that helps.

See Memcached::__construct() for more details.

drew010
  • 68,777
  • 11
  • 134
  • 162
  • Thanks ! I used memcache and not memcached . I will be moving to memcached now as they allow persistence connection . Is memcached just a new version of memcache ? Thanks – Pit Digger Jul 27 '12 at 22:55
  • 1
    Yes, `Memcached` is just a newer version that supports more features such as persistent connections, and CAS tokens. See [this question and accepted answer](http://stackoverflow.com/questions/1442411/using-memcache-vs-memcached-with-php) for more specifics. Use the `Memcached` extension where possible and not `memcache` – drew010 Jul 27 '12 at 23:07
  • Thank you . One more question . If I use http://php.net/manual/en/memcache.pconnect.php will that be causing any issues ?Since I have already have implemented memcache and wanted to see performance difference after installing memcached .If I dont see any major advantage with it the way I am using I will go with memcache. – Pit Digger Jul 28 '12 at 19:30
  • I don't think that should cause any issues. Give it a try and see if you notice a performance increase by using it. I wasn't aware of that function before you mentioned it. – drew010 Jul 28 '12 at 19:42